Implicit __init__ execution in multiple inheritance

R

rludwinowski

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

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

class C(A, B):
pass

C()

Why __init__ class B will not be automatic executed?
 
A

Arnaud Delobelle

rludwinowski said:
class A:
def __init__(self):
print("A__init__")

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

class C(A, B):
pass

C()


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()
 
B

Bruno Desthuilliers

Arnaud Delobelle a écrit :
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.

Note to the OP : Python's "methods" are attributes, so the normal
attribute lookup rules apply - which is why the lookup stops at the
first (in _mro_ order) '__init__' method found.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top