类不继承所有方法/变量

时间:2019-09-22 18:08:21

标签: python python-3.x class inheritance subclass

我有两个班级,一个是父母,一个是孩子。由于某些原因,当我从父级继承时,并非所有方法/变量都可用。具体来说,尝试访问__bar上的Child会返回错误,但在Parent上它会按预期运行。真的不确定这里发生了什么。这是一个简化的示例:

test.py:

class Parent:
    def __init__(self):
        self.__bar = 1

class Child(Parent):
    def __init__(self):
        super().__init__()
        print(self.__bar)

Child()

预期输出仅为1,但错误是:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    Child()
  File "test.py", line 8, in __init__
    print(self.__bar)
AttributeError: 'Child' object has no attribute '_Child__bar'

尽管.__bar是在Parent中定义的,但我打电话给super().__init__()来对其进行初始化。

0 个答案:

没有答案
相关问题