2012-02-06 120 views
5

有沒有辦法完成這樣的事情?我在Python的工作,但我不知道是否有辦法做到這一點在任何編程語言...繼承類屬性(python)

class Parent(): 
    class_attribute = "parent" 

    @staticmethod 
    def class_method(): 
     print __class__.class_attribute 

class Child(Parent): 
    class_attribute = "child" 

我知道我不能直接調用__class__。它只是一個例子,因爲我想要類似於對類本身的引用,因爲我希望子類根據其class_attribute採取不同的行爲。

然後應該輸出應該是這樣的:

> Parent.class_method() 
"parent" 
> Child.class_method() 
"child" 

我知道同樣的技術可以通過實例來完成。但我不想創建實例,因爲有時__init__方法中的代碼可能會很長並且要求很高,如果我經常想要調用class_method,我將不得不創建大量僅用於此一方法調用的實例。並且因爲class_attributeclass_method是靜態的,不會被實例更改。

+0

你只是在談論'靜態'功能? – Tigran 2012-02-06 20:09:17

回答

9

呃,聽起來像是你想有一個類方法,這並不奇怪與classmethod裝飾完成:

class Parent(object): 
    class_attribute = "parent" 

    @classmethod 
    def class_method(cls): 
     print cls.class_attribute 

class Child(Parent): 
    class_attribute = "child" 


>>> Parent.class_method() 
parent 
>>> Child.class_method() 
child 

或者,正如bgporter指出的那樣,你可以直接使用屬性來完成,而不需要任何方法。

+0

是的,這正是我想要的,非常感謝! – davekr 2012-02-06 20:16:55

+0

但考慮到文檔:「如果爲派生類調用類方法,那麼**派生類對象**作爲隱含的第一個參數傳遞」,這是否意味着派生類對象將以任何方式創建?因爲OP說要避免實例構造。 – Tigran 2012-02-06 20:24:13

+0

我想調用方法,因爲方法中的代碼實際上可能會做更復雜的事情,然後只是打印屬性。我雖然做一個更簡單的exmaple會讓我更容易解釋我想要的......所以@classmethod是一個解決方案 – davekr 2012-02-06 20:24:56

3

這只是工作在Python,有或沒有創建實例:

>>> class Parent(object): 
... attribute = "parent" 
... 
>>> class Child(Parent): 
... attribute = "child" 
... 
>>> p = Parent() 
>>> p.attribute 
'parent' 
>>> c = Child() 
>>> c.attribute 
'child' 
>>> Parent.attribute 
'parent' 
>>> Child.attribute 
'child' 
>>>