2014-10-10 169 views
0

我真的不知道如何描述這個問題夠好。所以,我認爲一個例子更有表現:python類靜態方法動態綁定靜態數據成員

class A: 
    c=1 
    @staticmethod 
    def b(): return A.c 

class B(A): 
    c=2 

我希望B.b()回報2。但事實並非如此。我會以哪種方式實現它?非常感謝。

+1

如果要訪問類屬性,爲什麼要使用靜態方法而不是類方法? – BrenBarn 2014-10-10 19:16:08

+0

哦耶穌。我的腦中必須有一聲槍響! – HuStmpHrrr 2014-10-10 19:20:14

回答

2

的問題是,您使用的是staticmethod和硬編碼類A,而不是使用classmethod,並使用cls說法。

試試這個:

class A: 
    c=1 
    @classmethod 
    def b(cls): return cls.c 

的文檔(上面鏈接)解釋的區別,但你可能想嘗試尋找堆棧溢出的問題,如What is the difference between @staticmethod and @classmethod in Python進行了較深入的討論。簡而言之:staticmethod基本上只是類名稱空間內的全局函數,而classmethod是類對象上的方法;如果你想使用任何類屬性(或類本身,如替代構造函數成語),你想要後者。

2

您必須使用類方法,以便您可以動態地引用類。像你目前使用的靜態方法沒有綁定到任何類,所以你必須靜態顯式引用A類。

class A(object): 
    c = 1 
    @classmethod 
    def b(cls): 
     return cls.c 

class B(A): 
    c = 2