[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Implicit __init__ execution in multiple inheritance

rludwinowski

2/16/2010 2:37:00 PM

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?
2 Answers

Arnaud Delobelle

2/16/2010 2:48:00 PM

0

rludwinowski <rludwinowski@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()

Bruno Desthuilliers

2/16/2010 3:13:00 PM

0

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

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.