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.
It just works in Python, with or without creating instances:
>>> 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'
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.