Pass python variable from object to parent
I'm writing a python program that wants to keep track of a status flag from several different places. I've done some reading to discover that a Python variable passed into a function can't necessarily be modified by that function (in my case it can't). As an example:
def testfunc(self, inVariable):
inVariable = 4
def main():
myVariable = 6
print myVariable
开发者_StackOverflow中文版 testfunc(myVariable)
print myVariable
In this situation, the output would be: 6 6
and the 4 would never be assigned to myVariable.
Realizing that this cannot be changed, does anyone have a good workaround for this situation? Global variables, perhaps?
The situation I am dealing with is much more complex than this one, so something like returning a value and assigning it is not an easy option for me.
Thanks!
Marlon
Three solutions:
pass it a collection object containing your data
def testFunc1(var): var[0] = 4 myvar = [6] testFunc1(myvar) print(myvar[0])
make the variable a global
myvar = None def testFunc2(): global myvar myvar = 4 myvar = 6 testFunc2() print(myvar)
I don't generally like global variables, but depending on what you're doing it may make sense.
return the variable from the function
def testFunc3(var): return 4 myvar = 6 myvar = testFunc3(myvar) print(myvar)
Edit: a fourth option; as per your declaration,
def testfunc(self, inVariable):
this appears to be a class method (passing self
as an argument). If the status flag is a class variable or instance variable, the method can change it as self.status = 4
and this change will be retained.
Global variables, perhaps?
Global variables are almost always a bad idea.
A variable in Python is just binding a name to a value, in testFunc
all you're doing is changing the value bound to inVariable
rather than changing the variable itself.
You'll need to pass an object to your function and modify its attributes. You use a built-in type like list
or dict
, but it's just as easy to create your own class:
>>> class Status(object):
... # Lazily use a class variable as a default for instance variables
... flag = 0
...
>>> def testFunc(status):
... status.flag = 4
...
>>> s = Status()
>>> s.flag = 6
>>> s.flag
6
>>> testFunc(s)
>>> s.flag
4
Thanks everyone for the good ideas. I ended up "cheating" on this one: the program is written with Qt so I was able to use signals and slots to accomplish my goal.
Using class variables is an interesting idea; it sort of tricks python into creating a variable that is mutable, correct? I think global variables may have been a good way to go if not for my alternative solution; this seems like one of the rare cases where they may have been a good idea.
Hopefully these answers will help others with similar problems as well.
Cheers
Marlon
精彩评论