0

How can I call python functions using dynamic variable names? This is an example:

class test(object):
    def __init__(self):
        self.a, self.b, self.c = 1, 2 ,3
    def __str__(self):
        return "a: " + str(self.a) + \
                          ", b: " + str(self.b) + \
                          ", c:" + str(self.c)       
    def inc_a(self):
        self.a += 1                          

t1 = test()
print(t1)
t1.inc_a() # this is what I DON'T want, individual increment functions
print(t1)

# I would like a inc that works like this:
# t1.inc(a) --> increase a by 1
# t1.inc(b) --> increase b by 1
# t1.inc(c) --> increase c by 1
# print(t1) 

Thx&kind regards

2
  • Yes it works, many thanks (already gave you a like)! I will accept it as solution soon. I am hoping, however, that somebody will come up with a solution without quotes in the function call. I like the setattr/getattr solution a lot, but I was thinking there could be a solution similar to R's eval(substitute()). (The exec-solution looks like an equivalent for R's eval(parse(text =)).) Commented Nov 2, 2017 at 9:20
  • I'm afraid, that won't be possible to do in python. if you're calling t.inc(a), a needs to be an already defined object/ variable else you'll get NameError. Commented Nov 2, 2017 at 10:07

1 Answer 1

2

You can simply do it like this, using exec :

class test(object):
    def __init__(self):
        self.a, self.b, self.c = 1, 2 ,3
    def __str__(self):
        return "a: " + str(self.a) + \
                          ", b: " + str(self.b) + \
                          ", c:" + str(self.c)       
    def inc(self, v):
        exec("self.%s += 1" % (v))

OUTPUT

>>> t= test()
>>> print(t)
a: 1, b: 2, c:3
>>> t.inc('a')
>>> print(t)
a: 2, b: 2, c:3
>>> t.inc('b')
>>> print(t)
a: 2, b: 3, c:3
>>> t.inc('c')
>>> print(t)
a: 2, b: 3, c:4

However it would be better in your case to use setattr along with getattr since you're trying to set values for class variables, so your inc method will look something like this:

def inc(self, v):
    setattr(self, v, getattr(self, v)+1)

Output : same as above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.