Question
Consider the following snippet of python code:
- class A(object):
- def __init__(self, a):
- self.a = a
- class B(A):
- def __init__(self, a, b):
- super(B, self).__init__(a)
- self.b = b
- class C(A):
- def __init__(self, a, c):
- super(C, self).__init__(a)
- self.c = c
- class D(B, C):
- def __init__(self, a, b, c, d):
- #super(D,self).__init__(a, b, c) ???
- self.d = d
How-To
Well, when dealing with multiple inheritance in general, your base classes (unfortunately) should be designed for multiple inheritance. Classes B and C in your example aren't, and thus you couldn't find a proper way to apply super in D.
One of the common ways of designing your base classes for multiple inheritance, is for the middle-level base classes to accept extra args in their __init__ method, which they are not intending to use, and pass them along to their super call.
Here's one way to do it in python:
- class A(object):
- def __init__(self, a):
- self.a = a
- def showA(self):
- print("A.a={}".format(self.a))
- class B(A):
- def __init__(self, b, **kw):
- self.b=b
- super(B, self).__init__(**kw)
- def showB(self):
- print("B.b={}".format(self.b))
- class C(A):
- def __init__(self, c, **kw):
- self.c=c
- super(C, self).__init__(**kw)
- def showC(self):
- print("C.c={}".format(self.c))
- class D(B,C):
- def __init__(self, a, b, c, d):
- super(D, self).__init__(a=a, b=b, c=c)
- self.d = d
- def showD(self):
- print("D.d={}".format(self.d))
- d = D(a='a', b='b', c='c', d='d')
- d.showA()
- d.showB()
- d.showC()
- d.showD()
Supplement
* Tutorialspoint - Python 3 - Object Oriented
沒有留言:
張貼留言