[newbie] super() and multiple inheritance
Steven Bethard
steven.bethard at gmail.com
Thu Dec 1 13:47:08 EST 2005
hermy wrote:
> As I understand it, using super() is the preferred way to call
> the next method in method-resolution-order. When I have parameterless
> __init__ methods, this works as expected.
> However, how do you solve the following simple multiple inheritance
> situation in python ?
>
> class A(object):
> def __init__(self,x):
> super(A,self).__init__(x)
> print "A init (x=%s)" % x
>
> class B(object):
> def __init__(self,y):
> super(B,self).__init__(y)
> print "B init (y=%s)" % y
>
> class C(A,B):
> def __init__(self,x,y):
> super(C,self).__init__(x,y) <-------- how to do this ???
> print "C init (x=%s,y=%s)" % (x,y)
Unfortunately, super() doesn't mix too well with hierarchies that change
the number of arguments to a method. One possibility:
class A(object):
def __init__(self, x, **kwargs):
super(A, self).__init__(x=x, **kwargs)
print "A init (x=%s)" % x
class B(object):
def __init__(self, y, **kwargs):
super(B, self).__init__(y=y, **kwargs)
print "B init (y=%s)" % y
class C(A,B):
def __init__(self, x, y):
super(C, self).__init__(x=x,y=y)
print "C init (x=%s,y=%s)" % (x,y)
Then you can get::
py> C(1, 2)
B init (y=2)
A init (x=1)
C init (x=1,y=2)
<__main__.C object at 0x00B9FA70>
But you have to make sure to always pass the **kwargs around.
STeVe
More information about the Python-list
mailing list