I’m having a problem with not being able to reference a member variable indirectly.
I have a class with a function which does one thing. This function uses a member variable during its execution, and which member variable it uses is dependent on the input parameter cmd. Here’s some code:
class Foo(object):
def __init__(self):
self.a = 0
self.b = 0
def bar(self, cmd):
if cmd == "do_this":
index = self.a
elif cmd == "do_that":
index = self.b
filename = "file-%d.txt" % index
fp = open("filename", "w")
# do some more things which depend on and *should* change
# the value of self.a or self.b
return
Now I understand why this code doesn’t do what I want. Because we are using the immutable int type, our variable index refers to the value of the member variable self.a or self.b, not self.a or self.b themselves. By the end of the function, index refers to a different valued integer, but self.a and self.b are unchanged.
I’m obviously thinking too C++-ish. I want something equivalent to
index = &(self.a)
filename = "file-%d.txt" % *index
How do I accomplish this in a Pythonic way?
There are any number of ways to do this–
setattrand the attribute name as a string, writing functions or methods which do the setting for each attribute, etc. One that is fairly clear and may be convenient isYour intuition to avoid using attribute names as strings is usually right (although that is easily as good a solution in this particular case), and the stock solution to avoiding looking up attributes and variables by strings is “use a dict”.