gpt4 book ai didi

python - 父访问在 Python 中子定义的类变量?

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:01 25 4
gpt4 key购买 nike

我正在学习 python 中的 OOP,我很惊讶地发现另一个 post父类可以访问子类中定义的类变量,如下例所示。我可以理解 child 可以访问在继承的父 bc 中定义的类变量(或者它不是继承而是其他东西?)。是什么使这成为可能,它是否意味着子类从父类(super class)继承时可以添加到(及其父类(super class)可以访问)的类变量池?

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__()

最佳答案

这个例子有点扭曲。父类的定义是不完整的,它引用了不存在的类变量,这只有在实例化类或子类化时才会显现出来。

如果您按如下方式子类化:

class Child2(Parent):
def __init__(self):
super(Child2, self).__init__()

然后实例化子类就不行了:

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'

您必须按如下方式修复您的 parent 才能使其正常工作:

class Parent(object):
ATTRS = None
def __init__(self):
if self.ATTRS:
for attr in self.ATTRS:
setattr(self, attr, 0)

它在您的原始示例中起作用的原因是 Python 是一种解释型语言,因此代码仅在运行时评估。

关于python - 父访问在 Python 中子定义的类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com