Implicit __init__ execution in multiple inheritance

Arnaud Delobelle arnodel at googlemail.com
Tue Feb 16 09:47:32 EST 2010


rludwinowski <rludwinowski at gmail.com> writes:

> class A:
>     def __init__(self):
>         print("A__init__")
>
> class B:
>     def __init__(self):
>         print("B__init__")
>
> class C(A, B):
>     pass
>
> C()
>
>>> A__init__
>
> Why __init__ class B will not be automatic executed?

Because it's documented behaviour?  By default, at initialisation, an
instance of C will go up the method resolution order and only execture
the first __init__() method found.  If you want to change this, you have
to do it explicitely within the __init__ method(s) of the parent
class(es).  E.g. try this (assuming Python 3 syntax):

class A:
    def __init__(self):
        super().__init__()
        print("A__init__")

class B:
    def __init__(self):
        super().__init__()
        print("B__init__")

class C(A, B):
    pass

C()



More information about the Python-list mailing list