Python:将值重新分配给变量(使用函数) [英] Python: Reassign value to variable (using a function)

查看:59
本文介绍了Python:将值重新分配给变量(使用函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python:如何通过引用传递变量?

如何将值重新分配给作为函数参数传递的变量?

How can I reassign a value to a variable that is passed as a function argument?

例如,我想要做的是:

foo = True

def convert(foo):
    if foo == True:
        foo = 'on'
    elif foo == False:
        foo = 'off'
    return foo

其中 foo 现在是一个字符串.上面方法的问题是,为了将 foo 从布尔类型更改为字符串类型,必须传递以下内容:

where foo is now a string. The problem with the method above is that in order to change foo from a boolean type to a string type the following must be passed:

foo = convert(foo)

而我正在做类似的事情:

whereas I am looking to do something like:

convert(foo)

foo.convert()

有什么想法吗?

推荐答案

foo = convert(foo)

是达到此目的的最干净,最明确的方法.如果您确定甚至需要将字符串重新分配给 bool 变量,这就是大多数人推荐的方法.

is the cleanest and most explicit way to achive this. This is the way most people would recommend, if you are sure you even need to reassign a string to a bool variable.

foo.convert()

是您可以在需要定义的类的实例上执行的操作.您可以做到,但这不值得麻烦.只需重新分配变量即可.

is something you can do on an instance of a class that you need to define. You can do it, but it's not worth the hassle. Just reassign the variable, that's it.

convert(foo) # actually, just convert()

也可以,但是您必须在 convert 函数中使用 global 关键字.不建议这样做,尤其是在很容易避免的情况下.

can also work, but you'd have to use the global keyword in the convert function. This is not recommended, especially when it's so easy to avoid.

In [1]: foo = True

In [2]: def convert():
   ...:    global foo
   ...:    foo = 'on' if foo else 'off'
   ...:     

In [3]: convert()

In [4]: foo
Out[4]: 'on'

这篇关于Python:将值重新分配给变量(使用函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆