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

oro*_*aki 10 python api serialization json

这适用于JSON API.我不想要:

if method_str == 'method_1':
    method_1()

if method_str == 'method_2':
    method_2()
Run Code Online (Sandbox Code Playgroud)

出于显而易见的原因,这不是最佳的 我如何以可重用的方式将地图字符串用于这样的方法(还要注意我需要将参数传递给被调用的函数).

这是一个例子:

进入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.
Run Code Online (Sandbox Code Playgroud)

致电:

# Either this
say_something(135487, 'a_465cc1', message='Hello World', volume='Loud')

# Or this (this is more preferable of course)
say_something(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 25

对于实例方法,请使用 getattr

>>> class MyClass(object):
...  def sayhello(self):
...   print "Hello World!"
... 
>>> m=MyClass()
>>> getattr(m,"sayhello")()
Hello World!
>>> 
Run Code Online (Sandbox Code Playgroud)

对于函数,您可以查看全局字典

>>> def sayhello():
...  print "Hello World!"
... 
>>> globals().get("sayhello")()
Hello World!
Run Code Online (Sandbox Code Playgroud)

在这种情况下,由于没有调用prove_riemann_hypothesis函数,sayhello因此使用默认函数()

>>> globals().get("prove_riemann_hypothesis", sayhello)()
Hello World!
Run Code Online (Sandbox Code Playgroud)

这种方法的问题在于您正在与其他任何内容共享命名空间.您可能希望防范它不应该使用的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!
Run Code Online (Sandbox Code Playgroud)


myf*_*web 6

使用getattr.例如:

class Test(object):
    def say_hello(self):
        print 'Hell no, world!!111'
    def test(self):
        getattr(self, 'say_hello')()
Run Code Online (Sandbox Code Playgroud)


Mik*_*ham 6

干净,安全的方法是将dict映射到函数名称.如果这些实际上是方法,那么最好的方法仍然是制作这样的词典,尽管getattr也是可用的.使用globalseval不安全和脏.