python中的多重继承与super()

时间:2016-05-13 09:35:38

标签: python inheritance

我的代码:

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(),我可以使用什么方法?

1 个答案:

答案 0 :(得分:0)

从object继承+修复你的“超级”调用

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)