繁体   English   中英

我将如何运行给定名称的函数?

[英]How would I run a function given its name?

我有大量的混合功能:

mix(a, b)
add(a, b)
sub(a, b)
xor(a, b)
...

这些函数都采用相同的输入并提供不同的输出,所有这些都是相同的类型。 但是,我不知道哪个函数必须在运行时运行。

我将如何实施这种行为?

示例代码:

def add(a, b):
    return a + b

def mix(a, b):
    return a * b

# Required blend -> decided by other code
blend_name = "add"
a = input("Some input")
b = input("Some other input")

result = run(add, a, b)  # I need a run function

我在网上查看过,但大多数搜索都会导致从控制台运行函数或如何定义函数。

在这种情况下,我不是很喜欢使用字典,所以这是我使用getattr方法。 虽然从技术上讲它几乎相同,原理也几乎相同,但至少对我来说代码看起来更干净

class operators():
    def add(self, a, b):
        return (a + b)

    def mix(self, a, b):
        return(a * b)


# Required blend -> decided by other code
blend_name = "add"
a = input("Some input")
b = input("Some other input")
method = getattr(operators, blend_name)
result = method(operators, a, b)
print(result) #prints 12 for input 1 and 2 for obvious reasons

编辑这是没有getattr编辑代码,它看起来更干净。 所以你可以让这个类成为模块并根据需要导入,添加新的运算符也很容易,而不用关心在两个地方添加一个运算符(在使用字典将函数存储为键/值的情况下)

class operators():

    def add(self, a, b):
        return (a + b)

    def mix(self, a, b):
        return(a * b)

    def calculate(self, blend_name, a, b):
        return(operators.__dict__[blend_name](self, a, b))


# Required blend -> decided by other code
oper = operators()
blend_name = "add"
a = input("Some input")
b = input("Some other input")
result = oper.calculate(blend_name, a, b)
print(result)

您可以创建一个字典,将函数名称映射到它们的函数对象并使用它来调用它们。 例如:

functions = {"add": add, "sub": sub}   # and so on
func = functions[blend_name]
result = func(a, b)

或者,更紧凑一点,但可能不太可读:

result = functions[blend_name](a, b)

您可以为模块使用globals()字典。

result = globals()[blend_name](a, b)

谨慎的做法是为blend_name的值添加一些验证

暂无
暂无

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

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