【问题标题】:How to call static method by reference in python [duplicate]如何在python中通过引用调用静态方法[重复]
【发布时间】:2017-07-05 14:17:51
【问题描述】:

请看下面的例子:

class MyClass(object):

    @staticmethod
    def __myStaticMethod(someArgs):
        pass

    MY_SPECIAL_METHOD_LIST = [
        __myStaticMethod
    ]

    @staticmethod
    def someOtherMethod():
        m = MyClass.MY_SPECIAL_METHOD_LIST[0]
        print(m)
        m()

如果我现在执行语句 MyClass.someOtherMethod() 我会得到一个异常:

<staticmethod object at 0x7fd672e69898>
Traceback (most recent call last):
  File "./test3.py", line 25, in <module>
    MyClass.someOtherMethod()
  File "./test3.py", line 21, in someOtherMethod
    m()
TypeError: 'staticmethod' object is not callable

显然m 包含对静态方法的引用。但我不能调用这个方法。为什么?我需要更改什么才能调用此方法?

【问题讨论】:

标签: python static-methods invoke


【解决方案1】:

为了从你的类中调用一个静态方法,你需要解包它。将m() 更改为m.__func__('params'),你会很好。

【讨论】:

  • 谢谢。这就是我一直在寻找的。​​span>
猜你喜欢
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2014-03-09
  • 1970-01-01
  • 2019-10-19
  • 2020-12-07
  • 2018-01-13
相关资源
最近更新 更多