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?
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
boolvariable.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.
can also work, but you’d have to use the
globalkeyword in theconvertfunction. This is not recommended, especially when it’s so easy to avoid.