Python: Reassign value to variable (using a function)

Possible Duplicate:
Python: How do I pass a variable by reference?

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

For instance, what I am looking to do is:

foo = True

def convert(foo):
    if foo == True:
        foo = 'on'
    elif foo == False:
        foo = 'off'
    return 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)

or,

foo.convert()

Any ideas?


foo = convert(foo)

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()

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'
链接地址: http://www.djcxy.com/p/20826.html

上一篇: 在Python中增加全局作用域的整数变量

下一篇: Python:重新赋值给变量(使用函数)