这是用于 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!
The problem通过这种方法,您可以与其中的其他内容共享名称空间。你可能想要防止不应该的 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!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)