动态函数变量名称

时间:2017-11-02 08:03:55

标签: python-3.x function class

如何使用动态变量名称调用python函数?这是一个例子:

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&亲切的问候

1 个答案:

答案 0 :(得分:2)

你可以使用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))

<强>输出

>>> 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

但是,在您的情况下使用setattrgetattr会更好,因为您正在尝试为类变量设置值,因此您的inc方法会显示某些内容像这样:

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

输出:与上述相同。