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++?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With