【问题标题】:Class Inheritance Error: Child object has no attribute 'a' [closed]类继承错误:子对象没有属性“a”[关闭]
【发布时间】:2023-04-02 23:30:01
【问题描述】:

考虑下面的代码sn-p

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)

我预期的输出是:

9 0

但错误消息指出“子”对象没有属性“a”。

如果我改为使用父母的 init 方法而不是 super,我会得到我想要的输出。

parent.__init__(self)

我看过其他帖子,super是实现继承的推荐方式。我的问题是如何使用super方法将init方法初始化的父类属性继承到子类中?

【问题讨论】:

  • 请改进你的缩进
  • 错字:把super(parent, self).__init__()改成super(child, self).__init__()

标签: python class oop inheritance


【解决方案1】:

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

输出:

9
0
0 9

【讨论】:

    【解决方案2】:

    正如@eyllanesc 在评论中提到的,这是一个错字。

    super() 应该在 'child' 对象上调用。

    super(child, self).__init__() 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 2021-08-25
      • 2017-02-09
      • 2013-08-05
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多