简体   繁体   English

动态函数变量名称

[英]Dynamic function variable name

How can I call python functions using dynamic variable names? 如何使用动态变量名称调用python函数? 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 致谢

You can simply do it like this, using exec : 您可以使用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: 但是,在您的情况下,最好将setattrgetattr一起使用,因为您正在尝试为类变量设置值,因此inc方法将如下所示:

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

Output : same as above. 输出:与上面相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM