2 回答

TA貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
您應(yīng)該將函數(shù)稱為對(duì)象而不是字符串,以便:
class test:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
def addition(self):
return self.a + self.b + self.c
def subtraction(self):
return self.a - self.b - self.c
test_action = {
'1': test.addition,
'2': test.subtraction
}
xxx = test(10,5,1)
for key, action in test_action.items():
print(key, action(xxx))
會(huì)輸出:
1 16
2 4

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
def main():
xxx = test(10,5,1)
for key,action in test_action.items():
if hasattr(xxx, action):
print "perforning: {}".format(action)
print xxx.__getattribute__(action)()
#op
perforning: addition
16
perforning: subtraction
4
添加回答
舉報(bào)