I\'m pretty much new in Python object oriented programming and I have trouble
understanding the super()
function (new style classes) especially when it comes to
Another not yet covered point is passing parameters for initialization of classes. Since the destination of super
depends on the subclass the only good way to pass parameters is packing them all together. Then be careful to not have the same parameter name with different meanings.
Example:
class A(object):
def __init__(self, **kwargs):
print('A.__init__')
super().__init__()
class B(A):
def __init__(self, **kwargs):
print('B.__init__ {}'.format(kwargs['x']))
super().__init__(**kwargs)
class C(A):
def __init__(self, **kwargs):
print('C.__init__ with {}, {}'.format(kwargs['a'], kwargs['b']))
super().__init__(**kwargs)
class D(B, C): # MRO=D, B, C, A
def __init__(self):
print('D.__init__')
super().__init__(a=1, b=2, x=3)
print(D.mro())
D()
gives:
[, , , , ]
D.__init__
B.__init__ 3
C.__init__ with 1, 2
A.__init__
Calling the super class __init__
directly to more direct assignment of parameters is tempting but fails if there is any super
call in a super class and/or the MRO is changed and class A may be called multiple times, depending on the implementation.
To conclude: cooperative inheritance and super and specific parameters for initialization aren't working together very well.