如何循环dict并将值用作对象的功能?

时间:2018-10-11 02:59:33

标签: python loops dictionary

我有一个值字典,并初始化一个对象。 词典值包含对象的所有模块,那么如何实现类似的功能?

test_action = {
    '1': 'addition',
    '2': 'subtraction'
}

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


def main():
    xxx = test(10,5,1)
    for key,action in test_action.items():
        print(xxx.action())

2 个答案:

答案 0 :(得分:0)

您应该将函数称为对象而不是字符串,以便:

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

将输出:

1 16
2 4

答案 1 :(得分:0)

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