用super()实现python中的多重继承

2024-04-26 06:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

class A():
    def __init__(self, a = 100):
        self.a = a

class B():
    def __init__(self, b = 200):
        self.b = b

class C(A,B):
    def __init__(self, a, b, c = 300):
        super().__init__(a)
        super().__init__(b)
        self.c = c

    def output(self):
        print(self.a)
        print(self.b)
        print(self.c)


def main():
    c = C(1,2,3)`enter code here`
    c.output()

main()

错误:

2
Traceback (most recent call last):
  File "inheritance.py", line 25, in <module>
    main()
  File "inheritance.py", line 23, in main
    c.output()
  File "inheritance.py", line 17, in output
    print(self.b)
AttributeError: 'C' object has no attribute 'b'

为什么它不能继承b? 这个代码怎么了??? 如何修改这个代码?你知道吗

如果我用A.或B替换supper(),它可以正常运行。 那么是什么导致了这个问题呢? 如果我不使用super(),我可以使用什么方法?你知道吗


Tags: 代码inpyselfoutputinitmaindef
1条回答
网友
1楼 · 发布于 2024-04-26 06:12:06

从对象继承+修复了你的“超级”调用

class A(object):
   def __init__(self, a = 100):
      self.a = a

class B(object):
   def __init__(self, b = 200):
      self.b = b

class C(A,B):
   def __init__(self, a, b, c = 300):
      A.__init__(self, a=a)
      B.__init__(self, b=b)
      self.c = c

   def output(self):
      print(self.a)
      print(self.b)
      print(self.c)

相关问题 更多 >