这用于 JSON API。 我不想拥有:
if method_str == 'method_1':
method_1()
if method_str == 'method_2':
method_2()
由于显而易见的原因,这不是最优的。我将如何以可重用的方式使用映射字符串到这样的方法(另请注意,我需要将参数传递给被调用的函数)。
这是一个例子:
传入的 JSON:
{
'method': 'say_something',
'args': [
135487,
'a_465cc1'
]
'kwargs': {
'message': 'Hello World',
'volume': 'Loud'
}
}
# JSON would be turned into Python with Python's built in json module.
结果调用:
# Either this
say_something(135487, 'a_465cc1', message='Hello World', volume='Loud')
# Or this (this is more preferable of course)
say_something(*args, **kwargs)
最佳答案
对于实例的方法,使用getattr
>>> class MyClass(object):
... def sayhello(self):
... print "Hello World!"
...
>>> m=MyClass()
>>> getattr(m,"sayhello")()
Hello World!
>>>
对于函数,你可以在全局字典中查找
>>> def sayhello():
... print "Hello World!"
...
>>> globals().get("sayhello")()
Hello World!
在这种情况下,由于没有名为 prove_riemann_hypothesis
的函数,因此使用默认函数 (sayhello
)
>>> globals().get("prove_riemann_hypothesis", sayhello)()
Hello World!
此方法的问题是您与其中的任何其他内容共享命名空间。您可能想要防范不应该的 json 调用方法。一个好的方法是像这样装饰你的函数
>>> json_functions={}
>>> def make_available_to_json(f):
... json_functions[f.__name__]=f
... return f
...
>>> @make_available_to_json
... def sayhello():
... print "Hello World!"
...
>>> json_functions.get("sayhello")()
Hello World!
>>> json_functions["sayhello"]()
Hello World!
>>> json_functions.get("prove_riemann_hypothesis", sayhello)()
Hello World!
关于Python:当只有方法的字符串名称时如何调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2203438/