Class attribute inheritance (python)

Is there a way to do something like this? I work in Python, but I'm not sure if there is a way to do this in any programming language ...

class Parent():
    class_attribute = "parent"

    @staticmethod
    def class_method():
        print __class__.class_attribute

class Child(Parent):
    class_attribute = "child"

I know that I cannot directly call __class__. This is just an example because I would like something like a reference to the class itself, because I want the child class to act differently based on its class_attribute.

And then the supposed conclusion should look like this:

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

, . , __init__ , class_method, , . class_attribute class_method .

+5
2

Er, , 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, , .

+9

It just works in Python with or without instantiation:

>>> 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'
>>> 
+3
source

All Articles