[英]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...
我在Python工作,但我不确定是否有办法在任何编程语言中做到这一点......
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. 我知道我不能直接调用
__class__
。 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. 它只是一个例子,因为我想要类似于类本身的引用,因为我希望子类基于其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. 但是我不想创建实例,因为有时
__init__
方法中的代码可能很长并且要求很高,如果我想经常调用class_method
,我将不得不创建大量用于这个方法调用的实例。 And because class_attribute
and class_method
are static and won't be changed by instances. 而由于
class_attribute
和class_method
是静态的,不会被实例进行更改。
Er, sounds like you want a classmethod, which not surprisingly is done with the classmethod
decorator: 呃,听起来你想要一个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
Or, as bgporter points out, you can do it directly with the attributes, with no need for the methods at all. 或者,正如bgporter指出的那样,你可以直接使用属性来完成它,而根本不需要这些方法。
It just works in Python, with or without creating instances: 它只适用于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.