【问题标题】:Call method from string inside class?从类内的字符串调用方法?
【发布时间】:2018-03-02 13:59:45
【问题描述】:

我正在尝试使用字符串值调用函数。这是我的问题的一个简单示例。如何正确拨打method(line)?我尝试了不同的解决方案并仅通过@staticmethod 获得了成功,但这不是我想要的。

class A():

    def prime(self, key):
        line = 'Good'
        method = getattr(A, key)
        method(line)

    def add1(self, string):
        print string + ' day!'

    def add2(self, string):
        print string + ' evening!'



def main():
    test = A()
    test.prime('add1')
    test.prime('add2')

if __name__ == "__main__":
    main()

【问题讨论】:

  • 可以正常调用的情况下为什么要变成字符串
  • 因为这是我的问题的简单示例。
  • 是否有理由需要传递字符串而不是对方法本身的引用? test.prime(A.add1),然后 def prime(self, method): method(self, "Good")`
  • 是的,因为用户可以访问参数并且将输入作为简单字符串更容易。我希望,现在更清楚了

标签: python string methods getattr


【解决方案1】:

您需要将self 传递给getattr 而不是类名:

method = getattr(self, key)
method(line)

另外,如果这是 Python 2,在大多数情况下,您应该从 object 继承,以使用 new-style classes

class A(object):

【讨论】:

  • @Gatto 不客气 :-)。如果此答案解决了您的问题,请考虑接受。
【解决方案2】:

使用operator.methodcaller:

def prime(self, key):
    operator.methodcaller(key, "Good")(self)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多