基于参数动态调用嵌套函数 [英] Dynamically calling nested functions based on arguments
本文介绍了基于参数动态调用嵌套函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有以下Python类:
If I have the following Python class:
class Test(object):
funcs = {
"me" : "action",
"action": "action",
"say" : "say",
"shout" : "say"
}
def dispatch(self, cmd):
def say:
print "Nested Say"
def action:
print "Nested Action"
# The line below gets the function name as a string,
# How can I call the nested function based on the string?
Test.funcs.get(cmd, "say")
能够执行以下操作:
>>> Test().dispatch("me")
Nested Action
>>> Test().dispatch("say")
Nested Say
推荐答案
我可能会这样做:
def register(dict_, *names):
def dec(f):
m_name = f.__name__
for name in names:
dict_[name] = m_name
return f
return dec
class Test(object):
commands = {}
@register(commands, 'foo', 'fu', 'fOo')
def _handle_foo(self):
print 'foo'
@register(commands, 'bar', 'BaR', 'bAR')
def _do_bar(self):
print 'bar'
def dispatch(self, cmd):
try:
return getattr(self, self.commands[cmd])()
except (KeyError, AttributeError):
# Command doesn't exist. Handle it somehow if you want to
# The AttributeError should actually never occur unless a method gets
# deleted from the class
现在,该类公开了一个 dict
,它的键是测试成员资格的命令。所有方法和字典只创建一次。
Now, the class exposes a dict
whose keys are commands for testing membership. All the methods and the dictionary are created only once.
t = Test()
if 'foo' in t.commands:
t.dispatch('foo')
for cmd in t.commands:
# Obviously this will call each method with multiple commands dispatched to it once
# for each command
t.dispatch(cmd)
Etc 。
这篇关于基于参数动态调用嵌套函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文