Multiple inheritance, super() and changing signature

Nagy László Zsolt gandalf at shopzeus.com
Fri Jun 3 10:06:12 EDT 2016


>> That's overly strict. As Raymond shows, it is easy to deal with
>> changing method signatures in *cooperative* classes. 
> I must watch that for sure.

All right, I have read this:

https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

There is still something I don't get: how to create cooperative classes
when some base classes share some of the parameters?

Here is an example modified from Raymond's post:

class A:
    def __init__(self, param1, param2, **kwds):
        self.param1 = param1
        self.param2 = param2
        super().__init__(**kwds)

class B:
    def __init__(self, param1, param3, **kwds):
        self.param1 = param1
        self.param3 = param3
        super().__init__(**kwds)


class X(A,B):
    def __init__(self, param1, param2, param3, **kwds):
        print("param1=",param1,"param2=",param2,"param3=",param3)
        super().__init__(param1=param1,param2=param2,param3=param3,**kwds)

print(X.__mro__)
x = X(1,2,3)


Result:

(<class '__main__.X'>, <class '__main__.A'>, <class '__main__.B'>,
<class 'object'>)
param1= 1 param2= 2 param3= 3
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    x = X(1,2,3)
  File "test.py", line 17, in __init__
    super().__init__(param1=param1,param2=param2,param3=param3,**kwds)
  File "test.py", line 5, in __init__
    super().__init__(**kwds)
TypeError: __init__() missing 1 required positional argument: 'param1'

I could only find this as a solution:

class Root:
    def __init__(self, **kwds):
        pass

class A(Root):
    def __init__(self, **kwds):
        self.param1 = kwds['param1']
        self.param2 = kwds['param2']
        super().__init__(**kwds)

class B(Root):
    def __init__(self, **kwds):
        self.param1 = kwds['param1']
        self.param3 = kwds['param3']
        super().__init__(**kwds)


class X(A,B):
    def __init__(self, param1, param2, param3, **kwds):
        print("param1=",param1,"param2=",param2,"param3=",param3)
        super().__init__(param1=param1,param2=param2,param3=param3,**kwds)

X(1,2,3)

But then self documentation and code completion becomes very problematic:

http://i.imgur.com/wzlh8uy.png





More information about the Python-list mailing list