【问题标题】:Python. How to call a function from a dictionary? [duplicate]Python。如何从字典中调用函数? [复制]
【发布时间】:2019-01-20 12:47:08
【问题描述】:

我想要一个字典,其中某个键调用一个值...该值是一个函数,我希望该函数能够执行。 下面是我的尝试,但我得到的只是它在内存中存储位置的值。

class Testing:
    def __init__(self):
        self.method = {'Method1': self.another, 'Method2': self.there}

    def launch(self, input):
        print(self.method[input])

    @staticmethod
    def another():
        print('This print statement should pop out.')

    @staticmethod
    def there():
        print('This should not appear.')

new = Testing()
new.launch('Method1')

我从中得到的结果是:

<function Testing.another at 0x01519540>

有没有办法做到这一点?

【问题讨论】:

  • def launch(self, input): self.method[input]() 就够了。
  • 只需在末尾添加一个括号,就像您在调用任何函数时所做的一样。

标签: python dictionary


【解决方案1】:

您缺少实际的函数调用:(注意末尾添加的()

def launch(self, input):
        print(self.method[input]())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    相关资源
    最近更新 更多