Tuesday, 15 February 2011

python - Multiple inheritance in python3 with different signatures -



python - Multiple inheritance in python3 with different signatures -

i have 3 classes: a, b , c.

c inherits a , b (in order). constructor signatures of a , b different. how can phone call __init__ methods of both parent classes?

my endeavour in code:

class a(object): def __init__(self, a, b): super(a, self).__init__() print('init {} arguments {}'.format(self.__class__.__name__, (a, b))) class b(object): def __init__(self, q): super(b, self).__init__() print('init {} arguments {}'.format(self.__class__.__name__, (q))) class c(a, b): def __init__(self): super(a, self).__init__(1, 2) super(b, self).__init__(3) c = c()

yields error:

traceback (most recent phone call last): file "test.py", line 16, in <module> c = c() file "test.py", line 13, in __init__ super(a, self).__init__(1, 2) typeerror: __init__() takes 2 positional arguments 3 given

i found this resource explains mutiple inheritance different set of arguments, suggest utilize *args , **kwargs utilize argument. consider ugly, since cannot see constructor phone call in kid class kind of parameters pass parent classes.

do not utilize super(baseclass, ...) unless know doing. first argument super() tells class skip when looking next method use. e.g. super(a, ...) @ mro, find a, start looking __init__ on next baseclass, not a itself. c, mro (c, a, b, object), super(a, self).__init__ find b.__init__.

for these cases, don't want utilize cooperative inheritance straight reference a.__init__ , b.__init__ instead. super() should used if methods calling have same signature or swallow unsupported arguments *args , **vargs. in case 1 super(c, self).__init__() phone call needed , next class in mro order take care of chaining on call.

putting differently: when utilize super(), can not know class next in mro, class improve back upwards arguments pass it. if isn't case, not utilize super().

calling base of operations __init__ methods directly:

class a(object): def __init__(self, a, b): print('init {} arguments {}'.format(self.__class__.__name__, (a, b))) class b(object): def __init__(self, q): print('init {} arguments {}'.format(self.__class__.__name__, (q))) class c(a, b): def __init__(self): # unbound functions, pass in self explicitly a.__init__(self, 1, 2) b.__init__(self, 3)

using cooperative super():

class a(object): def __init__(self, a=none, b=none, *args, **kwargs): super().__init__(*args, **kwargs) print('init {} arguments {}'.format(self.__class__.__name__, (a, b))) class b(object): def __init__(self, q=none, *args, **kwargs): super().__init__(*args, **kwargs) print('init {} arguments {}'.format(self.__class__.__name__, (q))) class c(a, b): def __init__(self): super().__init__(a=1, b=2, q=3)

python inheritance python-3.x multiple-inheritance

No comments:

Post a Comment