Python:当只有方法的字符串名称时如何调用方法?

标签 python json api serialization

这用于 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/

相关文章:

PHP 和 Python 接口(interface)

python - pandas 使用 python3 读取 csv 标准化日期

java - 无法使用 GWT 应用程序访问 freebase

api - 如何将 RESTful Web 服务添加到 Joomla 1.5+

swift - 使用 Swift 4 将 Base64 图像发布到 Web API

python - 检查 NumPy 数组是否包含另一个数组

Python difflib : not detecting changes

json - 以 json 格式返回 Eloquent 集合

ruby-on-rails - 使用 Rails 将外部 JSON 保存到数据库

json - 检索所有 CS :GO items via Steam API or endpoint