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

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

问题描述

这是用于 JSON API.我不想有:

if method_str == 'method_1':方法_1()如果 method_str == 'method_2':方法_2()

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

这是一个例子:

传入的 JSON:

<代码>{'方法':'say_something','参数':[135487,'a_465cc1']'夸格':{'message': '你好世界','音量':'大声'}}# JSON 将通过 Python 的内置 json 模块转换为 Python.

结果调用:

# 要么这个say_something(135487, 'a_465cc1', message='Hello World', volume='Loud')# 或者这个(当然这个更可取)say_something(*args, **kwargs)

解决方案

对于实例的方法,使用 getattr

<预><代码>>>>类 MyClass(对象):... def sayhello(self):...打印你好世界!"...>>>m=MyClass()>>>getattr(m,"sayhello")()你好,世界!>>>

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

<预><代码>>>>def sayhello():...打印你好世界!"...>>>globals().get("sayhello")()你好,世界!

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

<预><代码>>>>globals().get("prove_riemann_hypothesis", sayhello)()你好,世界!

这种方法的问题是您正在与其中的任何其他内容共享命名空间.您可能希望防范它不应该使用的 json 调用方法.一个很好的方法是像这样装饰你的函数

<预><代码>>>>json_functions={}>>>def make_available_to_json(f):... json_functions[f.__name__]=f...返回 f...>>>@make_available_to_json... def sayhello():...打印你好世界!"...>>>json_functions.get("sayhello")()你好,世界!>>>json_functions["sayhello"]()你好,世界!>>>json_functions.get("prove_riemann_hypothesis", sayhello)()你好,世界!

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).

Here is an example:

INCOMING 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.

Resulting call:

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

# Or this (this is more preferable of course)
say_something(*args, **kwargs)

解决方案

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!

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!

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天全站免登陆