簡體   English   中英

繼承類屬性(python)

[英]inheritance on class attributes (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是靜態的,不會被實例進行更改。

呃,聽起來你想要一個classmethod,這並不奇怪是用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指出的那樣,你可以直接使用屬性來完成它,而根本不需要這些方法。

它只適用於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'
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM