今天在写一个python多重继承,但是init该如何处理呢?
不动脑,写了一个
class A:
def __init__(self,sval):
print("A: rcd value: ",sval)
self.aval = sval
class B:
def __init__(self,sval,tval):
print("B: rcd 2 values: ",tval)
self.aval=sval
self.bval=tval
class C(A,B):
def __init__(self,a,b,c):
super().__init__(a)
super().__init__(b,c) # error here
c = C(1,2,3)
一想不对啊,super().init到底是调用的哪一个呢?
折腾半天,搞清楚了super的机制,直接奉上答案吧
class A:
def __init__(self,aval,**kwargs):
print("A: rcd value: ",aval)
self.aval = aval
super().__init__(**kwargs)
class B:
def __init__(self,b1val,b2val,**kwargs):
print("B: rcd 2 values: ",b2val)
self.b1val = b1val
self.b2val = b2val
super().__init__(**kwargs)
class C(A, B):
def __init__(self, a, b, c, **kwargs):
super().__init__(aval=a, b1val=b, b2val=c, **kwargs)
c = C(1, 2, 3)