Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of Mutlple inheritance in python

In [5]: class a(object):
   ...:     def __init__(self):
   ...:         print "In class a"
   ...:         self.a = 1
   ...:         
In [6]: class b(object):
   ...:     def __init__(self):
   ...:         print "In class b"
   ...:         self.b = 2
   ...:         
   ...:         

In [7]: class c(b, a):
   ...:     pass
   ...: 
In [8]: c.mro()
Out[8]: 
[<class '__main__.c'>,
 <class '__main__.b'>,
 <class '__main__.a'>,
 <type 'object'>]

In [9]: obj = c()
In class b

In [10]: obj.__dict__
Out[10]: {'b': 2}

The default __init__ method of class c is called on obj creation, which internally calls the __init__ of only class b.

As per my understanding, if I inherit from 2 class, my derived class object should have variables from both class (unless they are private to those classes).

My Question: Am I wrong in expecting my derived object to contain variables from both classes? If so, why? Shouldn't __init__ of class a also be called? What would have happened in language like C++?

like image 529
avasal Avatar asked Feb 13 '12 07:02

avasal


People also ask

How is multiple inheritance handled in Python?

Inheritance is the mechanism to achieve the re-usability of code as one class(child class) can derive the properties of another class(parent class). It also provides transitivity ie. if class C inherits from P then all the sub-classes of C would also inherit from P.

Which are the qualities of multiple inheritance?

Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or class may only inherit from one particular object or class.

What are issues with multiple inheritance in Python?

The Problem with Multiple Inheritance If you allow multiple inheritance then you have to face the fact that you might inherit the same class more than once. In Python as all classes inherit from object, potentially multiple copies of object are inherited whenever multiple inheritance is used.


1 Answers

In python, initialization methods from upper classes aren't called by default. To do that, you have to explicitly call them using super as follows:

class a(object):
    def __init__(self):
        super(a, self).__init__()
        print "In class a"
        self.a = 1

class b(object):
    def __init__(self):
        super(b, self).__init__()
        print "In class b"
        self.b = 2

class c(b, a):
    pass

obj = c()

Example output.

In class a
In class b

Edit: Regarding why this works this way, I'd say that it's a design decision based on The Zen of of Python:

Explicit is better than implicit.

like image 87
jcollado Avatar answered Oct 20 '22 17:10

jcollado