Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance on class attributes (python)

Is there a way to accomplish something like this? I work in Python, but I am not sure if there is a way to do it 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 I can't call __class__ directly. Its just an example, because I would want something like reference to the class itself, because I want the child class to act differently based on its class_attribute.

And then supposed output should be like this:

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

I know the same technique can be accomplish through the instances. But I don't want to create instances, because sometimes the code within the __init__ method could be long and demanding and if I would want to call class_method often, I would have to create plenty of instances used just for this one method call. And because class_attribute and class_method are static and won't be changed by instances.

like image 888
davekr Avatar asked Feb 06 '12 20:02

davekr


1 Answers

Er, sounds like you want a classmethod, which not surprisingly is done with the classmethod decorator:

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

Or, as bgporter points out, you can do it directly with the attributes, with no need for the methods at all.

like image 58
Daniel Roseman Avatar answered Sep 26 '22 14:09

Daniel Roseman