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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With