Python 类继承错误:子对象没有属性';a';
考虑下面的代码片段Python 类继承错误:子对象没有属性';a';,python,class,oop,inheritance,Python,Class,Oop,Inheritance,考虑下面的代码片段 class parent(object): def __init__(self): self.a = 0 class child(parent): def __init__(self): super(parent, self).__init__() self.b = 9 def func(self): print(self.a, self.b) c = child() print(c.
class parent(object):
def __init__(self):
self.a = 0
class child(parent):
def __init__(self):
super(parent, self).__init__()
self.b = 9
def func(self):
print(self.a, self.b)
c = child()
print(c.b)
print(c.a)
我期望的结果是:
九,
0
但错误消息指出“child”对象没有属性“a”
如果我改用parentsinit方法而不是super,我将获得所需的输出
parent.__init__(self)
我从其他帖子中读到,super是实现继承的推荐方法。我的问题是如何使用super方法将init方法初始化的父类属性继承到子类中?在python 3中,init方法中对
super()
的调用大大简化:
class parent(object):
def __init__(self):
self.a = 0
class child(parent):
def __init__(self):
super().__init__()
self.b = 9
def func(self):
print(self.a, self.b)
c = child()
print(c.b)
print(c.a)
print(c.func())
输出:
正如@eyllanesc在评论中提到的,这是一个打字错误 应该对“child”对象调用super()
super(child, self).__init__()
请改进您的标识类型:将
super(父,自)更改为super(子,自)更改为super(子,自)
super(child, self).__init__()