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?
if/elifchain is very often best replaced with a dict ({'do_this': self.a, 'do_that': self.b}).