2011-07-04 20 views
1

當一個靜態方法被調用時,有沒有什麼辦法讓它知道它從哪個子類被調用?如何從python中的@staticmethod函數中找到我稱爲的類?

(我知道,這是非常不OO並可能在一個良好的書面程序永遠是有用的,但我想知道,如果語言提供它)

例如:

class A(object): 
    @staticmethod 
    def foo(): 
    print 'bar' 
    # *** I would like to print either 'A' or 'B' here 

class B(A): 
    pass 

A.foo() 
B.foo() 

回答

9

爲此,您必須使用@classmethod而不是@staticmethod。隨着一個類的方法,你要傳遞的第一個參數類的引用:

class A(object): 
    @classmethod 
    def foo(cls): 
    print cls.__name__ 
    # *** I would like to print either 'A' or 'B' here 

class B(A): 
    pass 

A.foo() 
B.foo() 

輸出:http://codepad.org/bW3E51r9

一個

相關問題