Python Multiple Inheritance - shahzade baujiti

Breaking

Wednesday, April 24, 2019

Python Multiple Inheritance

Python Multiple Inheritance

Python supports multiple inheritance too. It allows us to inherit multiple parent classes. We can derive a child class from more than one base (parent) classes.

Image Representation



The multiderived class inherits the properties of both classes base1 and base2.

Let's see the syntax of multiple inheritance in Python.

Python Multiple Inheritance Syntax
class DerivedClassName(Base1, Base2, Base3): 
    <statement-1> 
    . 
    . 
    . 
    <statement-N>  

Or

class Base1: 
    pass 
 
class Base2: 
    pass 
 
class MultiDerived(Base1, Base2): 
    pass  

Python Multiple Inheritance Example

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print("first")

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print("second")

class Third(Second, First):
  def __init__(self):
    super(Third, self).__init__()
    print("third")

Third();

Output:
first 
second 
third 

Why super () keyword

The super() method is most commonly used with __init__ function in base class. This is usually the only place where we need to do some things in a child then complete the initialization in the parent.

See this example:
class Child(Parent): 
    def __init__(self, stuff): 
        self.stuff = stuff 
        super(Child, self).__init__() 
Composition in Python

Composition is used to do the same thing which can be done by inheritance.

No comments:

Post a Comment