python - 根据参数动态调用嵌套函数

标签 python nested closures

如果我有以下 Python 类:

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,其键是用于测试成员资格的命令。所有方法和字典仅创建一次。

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)

等等

关于python - 根据参数动态调用嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4273998/

相关文章:

python - 如何在pytest中测试类层次结构?

python - 使用 Excel Pandas 中的浮点值填充字典时出现问题

python - Pandas DataFrame 中的字典嵌套列表

Swift - 使用闭包的代码使用给定代码查找两个数字的总和

javascript - 一堆小闭包 vs 一个大闭包

swift - 在方法参数中隐式解包可选闭包

python - 如何将 RGB 图像转换为 numpy 数组?

python - Scrapy 如何从多个页面抓取项目?

python - 嵌套根据用户输入创建的多个字典

python - python 3中嵌套字典的排序列表