Python:只有方法的字符串名称时,如何调用方法? [英] Python: How do you call a method when you only have the string name of the method?

查看:136
本文介绍了Python:只有方法的字符串名称时,如何调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在JSON API中使用的. 我不想拥有:

This is for use in a JSON API. I don't want to have:

if method_str == 'method_1':
    method_1()

if method_str == 'method_2':
    method_2()

出于明显的原因,这不是最佳选择.我将如何以可重用的方式将映射字符串用于此类方法(还请注意,我需要将参数传递给被调用的函数).

For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in arguments to the called functions).

这里是一个例子:

传入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

For methods of instances, use getattr

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

对于功能,您可以查看全局字典

For functions you can look in the global dict

>>> def sayhello():
...  print "Hello World!"
... 
>>> globals().get("sayhello")()
Hello World!

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

In this case, since there is no function called prove_riemann_hypothesis the default function (sayhello) is used

>>> globals().get("prove_riemann_hypothesis", sayhello)()
Hello World!

此方法的问题是您要与其中的任何其他名称空间共享.您可能想防止不应使用的json调用方法.做到这一点的一种好方法是装饰这样的功能

The problem with this approach is that you are sharing the namespace with whatever else is in there. You might want to guard against the json calling methods it is not supposed to. A good way to do this is to decorate your functions like this

>>> 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:只有方法的字符串名称时,如何调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆