class A: def __init__(self): print("A",end=" ") super().__init__() class B: def __init__(self): print("B",end=" ") super().__init__() class C(A,B): def __init__(self): print("C",end=" ") A.__init__(self) B.__init__(self) print("MRO:",[x.__name__ for x in C.__mro__]) C()執行結果為:
MRO: ['C', 'A', 'B', 'object']
C A B B
class commonBase: def __init__(self): print("commonBase") super().__init__() class base1(commonBase): def __init__(self): print("base1") super().__init__() class base2(commonBase): def __init__(self): print("base2") super().__init__() class myClass(base1,base2): def __init__(self,arg): print("my base") super().__init__(arg) myClass(10)執行結果為:
my base
Traceback (most recent call last):
File "C:UsersmengmaDesktopdemo.py", line 20, in <module>
myClass(10)
File "C:UsersmengmaDesktopdemo.py", line 19, in __init__
super().__init__(arg)
TypeError: __init__() takes 1 positional argument but 2 were given
class commonBase: def __init__(self,*args,**kwargs): print("commonBase") super().__init__() class base1(commonBase): def __init__(self,*args,**kwargs): print("base1") super().__init__(*args,**kwargs) class base2(commonBase): def __init__(self,*args,**kwargs): print("base2") super().__init__(*args,**kwargs) class myClass(base1,base2): def __init__(self,arg): print("my base") super().__init__(arg) myClass(10)執行結果為:
my base
base1
base2
commonBase