[英]Parent accessing class variable defined in child in Python?
I am learning OOP in python, and I am surprised to find in another post that a parent class can access a class variable defined in child, like the example below. 我正在用python学习OOP,并且很惊讶地在另一篇文章中发现父类可以访问child中定义的类变量,如下面的示例。 I can understand that child can access a class variable defined in parent bc of inheritance (or is it not inheritance but something else?). 我可以理解,子级可以访问在父级bc继承中定义的类变量(或者不是继承而是其他?)。 What makes this possible and does it imply a pool of class variables that a subclass can adds to (and its superclasses can access) when it inherits from a superclass? 是什么使得这成为可能,并且是否意味着当子类从超类继承时,子类可以添加到(并且其超类可以访问)的类变量池?
class Parent(object):
def __init__(self):
for attr in self.ATTRS: // accessing class variable defined in child?
setattr(self, attr, 0)
class Child(Parent):
#class variable
ATTRS = ['attr1', 'attr2', 'attr3']
def __init__(self):
super(Child, self).__init__()
The example is a bit twisted. 这个例子有点扭曲。 The definition of the parent class is not complete, it references non-existing class variables, which only becomes apparent when instantiating the class or sub-classing it. 父类的定义不完整,它引用了不存在的类变量,只有在实例化该类或对其进行子分类时,该变量才变得明显。
If you subclass as follows: 如果您按以下方式子类化:
class Child2(Parent):
def __init__(self):
super(Child2, self).__init__()
Then instantiating the child class won't work: 然后实例化子类将不起作用:
Traceback (most recent call last):
File "./cl.py", line 25, in <module>
y=Child2()
File "./cl.py", line 20, in __init__
super(Child2, self).__init__()
File "./cl.py", line 6, in __init__
for attr in self.ATTRS:
AttributeError: 'Child2' object has no attribute 'ATTRS'
You would have to fix your parent as follows to make it work: 您必须按照以下步骤修复您的父母,以使其正常工作:
class Parent(object):
ATTRS = None
def __init__(self):
if self.ATTRS:
for attr in self.ATTRS:
setattr(self, attr, 0)
The reason it works in your original example is that Python is an interpreted language, so the code is only evaluated at run-time. 它在您的原始示例中起作用的原因是Python是一种解释型语言,因此该代码仅在运行时进行评估。
父不访问类变量,因为self
在__init__(self)
是一个实例Child
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.