为了账号安全,请及时绑定邮箱和手机立即绑定

如何循环 dict 并将该值用作对象的函数?

如何循环 dict 并将该值用作对象的函数?

繁华开满天机 2021-07-08 19:48:18
我有一个值字典并初始化一个对象。字典值包含对象的所有模块,那么我怎样才能实现这样的目标呢?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.cdef main():    xxx = test(10,5,1)    for key,action in test_action.items():        print(xxx.action())
查看完整描述

2 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

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


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


查看完整回答
反对 回复 2021-07-13
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

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


查看完整回答
反对 回复 2021-07-13
  • 2 回答
  • 0 关注
  • 166 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信