繁体   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