2017-02-16 75 views
0

請看下面的例子:如何通過引用在Python中調用靜態方法

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包含一個參考靜態方法。但我不能稱這種方法。爲什麼?爲了調用這個方法,我需要改變什麼?

+1

在這裏看:http://stackoverflow.com/questions/12718187/calling-class-staticmethod-within-the-class-body – haffla

+0

@haffla:很好找。謝謝。 –

+0

有趣。我尋找答案,但沒有遇到那個。感謝名單。 –

回答

0

爲了從你的類中調用靜態方法,你需要解開它。將m()更改爲m.__func__('params'),您會很好。

+0

謝謝。這就是我一直在尋找的。 –