简体   繁体   English

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

[英]How do I loop dict and use the value as functions of an object?

I have a dictionary of values and initialize an object. 我有一个值字典并初始化一个对象。 The dictionary values contains all the modules of the object, so how can I achieve something like this? 字典值包含对象的所有模块,那么如何实现这样的目标?

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

You should refer to the functions as objects rather than strings, so that: 您应该将函数称为对象而不是字符串,以便:

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

would output: 将输出:

1 16
2 4
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

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

相关问题 如何使用for循环遍历函数? - How do I loop through functions with a for loop? 如何将值附加到字典键? (AttributeError:“ str”对象没有属性“ append”) - How do I append a value to dict key? (AttributeError: 'str' object has no attribute 'append') 什么内部函数决定价值和项目使用,我如何覆盖它们? - What internal function does dict value and items use, and how do I overwrite them? 如何在 Python 中使用另一个 Class 中的字典进行循环 - How Do I For loop With A Dict in Python That Is In Another Class 我们如何通过更改变量从 object 获取 dict 值 - How do we get dict value from object with changing variable 在 Python 中得到“字典中没有书籍属性”,当使用点获取字典值时,就像我在 Jinja 模板中所做的那样 - Got “there is no books attribute in the dict” in Python when use dot to get the dict value like I do in Jinja template 如何在dict中的另一个值旁边添加值? - How do I add a value next to another value in dict? Python:如何在字典调用中使用变量值? - Python: How do you use a variable value in a Dict Call? 如何从用户输入正确添加到字典并使用 for 循环打印字典? - How do I properly add to a dict from user input and print the dict with a for loop? Python 字典键错误。 如何遍历嵌套字典并检查键 - Python Dict Key Error. How do I loop through nested dict and check for a key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM