Skip to content

Inheritance in Python

Inheritance in Python: Building on Foundations

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or derived class) to inherit attributes and behaviors from an existing class (superclass or base class). This mechanism promotes code reuse, extensibility, and the creation of a hierarchical structure among classes. In Python, inheritance is implemented with a straightforward syntax, emphasizing simplicity and flexibility.

What is Inheritance in Python?

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class). The derived class inherits all the features from the base class and can have additional features of its own. Inheritance is one of the most important aspects of OOP. It provides code reusability to the program because we do not have to write the same code again and again. We can just inherit the properties of one class into another class. Let’s see how to implement inheritance in Python.

Super Class

The class whose features are inherited is known as a superclass(or a base class or a parent class).

Sub Class

The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.

Reusability

Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.

Diagrammatic Representation of Inheritance

Inheritance in Python


  classDiagram
    Animal <|-- Dog
    Animal <|-- Cat
    Animal <|-- Horse
    Animal : +int age
    Animal : +void eat()
    Dog : +void bark()
    Cat : +void meow()
    Horse : +void neigh()

Inheritance

In this diagram, three classes are inherited from the AnimalAnimal class. These three classes are the subclasses of the AnimalAnimal class. The AnimalAnimal class is the superclass of all the three classes. The DogDog, CatCat, and HorseHorse classes inherit the AnimalAnimal class. They are the subclasses of the AnimalAnimal class. The DogDog, CatCat, and HorseHorse classes can have additional properties that are not in the AnimalAnimal class. They can have their own properties unique to each of them. The DogDog class can have a bark()bark() method. The CatCat class can have a meow()meow() method. The HorseHorse class can have a neigh()neigh() method. All these methods are unique to each of the subclasses. But the eat()eat() method is common to all the subclasses. It is inherited from the AnimalAnimal class. This is how inheritance works.

Syntax of Inheritance in Python

Syntax of Inheritance in Python
class BaseClass:
  Body of base class
 
class DerivedClass(BaseClass, [BaseClass2, BaseClass3, ...]):
    Body of derived class
Syntax of Inheritance in Python
class BaseClass:
  Body of base class
 
class DerivedClass(BaseClass, [BaseClass2, BaseClass3, ...]):
    Body of derived class

In the above example, we have created two classes named BaseClassBaseClass and DerivedClassDerivedClass. The DerivedClassDerivedClass is derived from the BaseClassBaseClass. The BaseClassBaseClass is the superclass and the DerivedClassDerivedClass is the subclass. The DerivedClassDerivedClass is derived from the BaseClassBaseClass using the syntax class DerivedClass(BaseClass):class DerivedClass(BaseClass):. The BaseClassBaseClass is passed as an argument to the DerivedClassDerivedClass. The BaseClassBaseClass is the superclass and the DerivedClassDerivedClass is the subclass. The DerivedClassDerivedClass inherits the features of the BaseClassBaseClass. The BaseClassBaseClass is also called the parent class and the DerivedClassDerivedClass is also called the child class. You can use multiple parent classes by separating them with a comma. For example, class DerivedClass(BaseClass1, BaseClass2, BaseClass3):class DerivedClass(BaseClass1, BaseClass2, BaseClass3):.

Example of Inheritance in Python

inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()
inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()

Output:

command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101
command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101

In the above example, we have created two classes named PersonPerson and StudentStudent. The StudentStudent class is derived from the PersonPerson class. The PersonPerson class is the superclass and the StudentStudent class is the subclass. The StudentStudent class inherits the features of the PersonPerson class. The PersonPerson class has two instance variables named namename and ageage. The StudentStudent class has three instance variables named namename, ageage, and rollroll. The StudentStudent class has a method named show_details()show_details() that prints the namename, ageage, and rollroll variables. The StudentStudent class has a constructor that takes three parameters namename, ageage, and rollroll. The super()super() function is used to call the constructor of the superclass. The super()super() function is used in the __init__()__init__() method of the StudentStudent class. The super()super() function is also used to call the show_details()show_details() method of the superclass.

init() method in Inheritance

In Python, You can call the Parent class’s __init__()__init__() method by the following two ways:

  1. ParentClassName.__init__(self, args)ParentClassName.__init__(self, args)
  2. super().__init__(args)super().__init__(args)

ParentClassName.init(self, args)

In this method, you have to specify the name of the parent class in the __init__()__init__() method. You have to pass the selfself keyword as the first argument to the __init__()__init__() method. You have to pass the arguments of the __init__()__init__() method of the parent class as the second argument to the __init__()__init__() method. Let’s see an example of this method.

inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        Person.__init__(self, name, age)
        self.roll = roll
 
    def show_details(self):
        Person.show_details(self)
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()
inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        Person.__init__(self, name, age)
        self.roll = roll
 
    def show_details(self):
        Person.show_details(self)
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()

Output:

command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101
command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101

In the above example, we have created two classes named PersonPerson and StudentStudent. The StudentStudent class is derived from the PersonPerson class. The PersonPerson class is the superclass and the StudentStudent class is the subclass. The StudentStudent class inherits the features of the PersonPerson class. The PersonPerson class has two instance variables named namename and ageage. The StudentStudent class has three instance variables named namename, ageage, and rollroll. The StudentStudent class has a method named show_details()show_details() that prints the namename, ageage, and rollroll variables. The StudentStudent class has a constructor that takes three parameters namename, ageage, and rollroll. The Person.__init__(self, name, age)Person.__init__(self, name, age) statement is used to call the constructor of the superclass. The Person.show_details(self)Person.show_details(self) statement is used to call the show_details()show_details() method of the superclass.

super() method in Inheritance

In python, super()super() method is used to access the methods and properties of the parent class. The super()super() method returns the proxy object that allows you to refer parent class by super()super(). The super()super() method is useful for accessing inherited methods that have been overridden in a class. The super()super() method can be used to call the __init__()__init__() method of the parent class from the child class so that you don’t need to rewrite the code in the child class. Let’s see an example of this method.

inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()
inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()

Output:

command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101
command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101

In the above example, we have created two classes named PersonPerson and StudentStudent. The StudentStudent class is derived from the PersonPerson class. The PersonPerson class is the superclass and the StudentStudent class is the subclass. The StudentStudent class inherits the features of the PersonPerson class. The PersonPerson class has two instance variables named namename and ageage. The StudentStudent class has three instance variables named namename, ageage, and rollroll. The StudentStudent class has a method named show_details()show_details() that prints the namename, ageage, and rollroll variables. The StudentStudent class has a constructor that takes three parameters namename, ageage, and rollroll. The super().__init__(name, age)super().__init__(name, age) statement is used to call the constructor of the superclass. The super().show_details()super().show_details() statement is used to call the show_details()show_details() method of the superclass.

Overriding Methods in Inheritance

In Python, you can override the methods of the superclass in the subclass. You can override the methods of the superclass by creating a method with the same name in the subclass. Let’s see an example of this.

inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()
inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()

Output:

command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101
command
C:\Users\username>python inheritance.py
Name: John
Age: 20
Roll: 101

In the above example, we have created two classes named PersonPerson and StudentStudent. The StudentStudent class is derived from the PersonPerson class. The PersonPerson class is the superclass and the StudentStudent class is the subclass. The StudentStudent class inherits the features of the PersonPerson class. The PersonPerson class has two instance variables named namename and ageage. The StudentStudent class has three instance variables named namename, ageage, and rollroll. The StudentStudent class has a method named show_details()show_details() that prints the namename, ageage, and rollroll variables. The StudentStudent class has a constructor that takes three parameters namename, ageage, and rollroll. The super().__init__(name, age)super().__init__(name, age) statement is used to call the constructor of the superclass. The super().show_details()super().show_details() statement is used to call the show_details()show_details() method of the superclass.

Types of Inheritance in Python

There are five types of inheritance in Python. They are:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

Types of Inheritance in Python


  graph LR
    A[Inheritance] --> B[Single Inheritance]
    A --> C[Multiple Inheritance]
    A --> D[Multilevel Inheritance]
    A --> E[Hierarchical Inheritance]
    A --> F[Hybrid Inheritance]

Types of Inheritance

Single Inheritance

In single inheritance, a class is allowed to inherit from only one class. It is the simplest form of inheritance in which a class inherits from only one base class. Let’s see an example of single inheritance.

Diagrammatic Representation of Single Inheritance

Single Inheritance in Python


  classDiagram
    Person <|-- Student
    Person : +string name
    Person : +int age
    Person : +void show_details()
    Student : +int roll
    Student : +void show_details()

Single Inheritance

single_inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()
single_inheritance.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show_details(self):
        print('Name:', self.name)
        print('Age:', self.age)
 
class Student(Person):
    def __init__(self, name, age, roll):
        super().__init__(name, age)
        self.roll = roll
 
    def show_details(self):
        super().show_details()
        print('Roll:', self.roll)
 
student1 = Student('John', 20, 101)
student1.show_details()

Output:

command
C:\Users\username>python single_inheritance.py
Name: John
Age: 20
Roll: 101
command
C:\Users\username>python single_inheritance.py
Name: John
Age: 20
Roll: 101

In the above example, we have created two classes named PersonPerson and StudentStudent. The StudentStudent class is derived from the PersonPerson class. The PersonPerson class is the superclass and the StudentStudent class is the subclass. The StudentStudent class inherits the features of the PersonPerson class. The PersonPerson class has two instance variables named namename and ageage. The StudentStudent class has three instance variables named namename, ageage, and rollroll. The StudentStudent class has a method named show_details()show_details() that prints the namename, ageage, and rollroll variables. The StudentStudent class has a constructor that takes three parameters namename, ageage, and rollroll. The super().__init__(name, age)super().__init__(name, age) statement is used to call the constructor of the superclass. The super().show_details()super().show_details() statement is used to call the show_details()show_details() method of the superclass.

Multiple Inheritance

In multiple inheritance, a class is allowed to inherit from more than one class. It is the process of deriving a new class that inherits the attributes from two or more classes. The derived class can have its own features in addition to the features of the base classes. Let’s see an example of multiple inheritance.

Diagrammatic Representation of Multiple Inheritance

Multiple Inheritance in Python


  classDiagram
    Father <|-- Child
    Mother <|-- Child
    Father : +string nature
    Mother : +string kind
    Father : +void get_nature()
    Mother : +void get_kind()
    Child : +void get_details()

Multiple Inheritance

multiple_inheritance.py
class Father:
    def __init__(self, nature):
        self.nature = nature
 
    def get_nature(self):
        print('Nature:', self.nature)
 
class Mother:
    def __init__(self, kind):
        self.kind = kind
 
    def get_kind(self):
        print('Kind:', self.kind)
 
class Child(Father, Mother):
    def __init__(self, nature, kind):
        Father.__init__(self, nature)
        Mother.__init__(self, kind)
 
    def get_details(self):
        self.get_nature()
        self.get_kind()
 
child1 = Child('Good', 'Good')
child1.get_details()
multiple_inheritance.py
class Father:
    def __init__(self, nature):
        self.nature = nature
 
    def get_nature(self):
        print('Nature:', self.nature)
 
class Mother:
    def __init__(self, kind):
        self.kind = kind
 
    def get_kind(self):
        print('Kind:', self.kind)
 
class Child(Father, Mother):
    def __init__(self, nature, kind):
        Father.__init__(self, nature)
        Mother.__init__(self, kind)
 
    def get_details(self):
        self.get_nature()
        self.get_kind()
 
child1 = Child('Good', 'Good')
child1.get_details()

Output:

command
C:\Users\username>python multiple_inheritance.py
Nature: Good
Kind: Good
command
C:\Users\username>python multiple_inheritance.py
Nature: Good
Kind: Good

In the above example, we have created three classes named FatherFather, MotherMother, and ChildChild. The ChildChild class is derived from the FatherFather and MotherMother classes. The FatherFather and MotherMother classes are the superclasses and the ChildChild class is the subclass. The ChildChild class inherits the features of the FatherFather and MotherMother classes. The FatherFather class has an instance variable named naturenature. The MotherMother class has an instance variable named kindkind. The FatherFather class has a method named get_nature()get_nature() that prints the naturenature variable. The MotherMother class has a method named get_kind()get_kind() that prints the kindkind variable. The ChildChild class has a method named get_details()get_details() that calls the get_nature()get_nature() and get_kind()get_kind() methods of the FatherFather and MotherMother classes respectively. The ChildChild class has a constructor that takes two parameters naturenature and kindkind. The Father.__init__(self, nature)Father.__init__(self, nature) statement is used to call the constructor of the FatherFather class. The Mother.__init__(self, kind)Mother.__init__(self, kind) statement is used to call the constructor of the MotherMother class.

Multilevel Inheritance

In multilevel inheritance, a class is allowed to inherit from a derived class. It is the process of deriving a new class from already derived class. Let’s see an example of multilevel inheritance.

Diagrammatic Representation of Multilevel Inheritance

Multilevel Inheritance in Python


  classDiagram
    Father <|-- Child
    Child <|-- GrandChild
    Father : +string nature
    Child : +string kind
    GrandChild : +string behavior
    Father : +void get_nature()
    Child : +void get_kind()
    GrandChild : +void get_behavior()

Multilevel Inheritance

multilevel_inheritance.py
class Father:
    def __init__(self, nature):
        self.nature = nature
 
    def get_nature(self):
        print('Nature:', self.nature)
 
class Child(Father):
    def __init__(self, nature, kind):
        super().__init__(nature)
        self.kind = kind
 
    def get_kind(self):
        print('Kind:', self.kind)
 
class GrandChild(Child):
    def __init__(self, nature, kind, behavior):
        super().__init__(nature, kind)
        self.behavior = behavior
 
    def get_behavior(self):
        print('Behavior:', self.behavior)
 
grandchild1 = GrandChild('Good', 'Good', 'Good')
grandchild1.get_nature()
grandchild1.get_kind()
grandchild1.get_behavior()
multilevel_inheritance.py
class Father:
    def __init__(self, nature):
        self.nature = nature
 
    def get_nature(self):
        print('Nature:', self.nature)
 
class Child(Father):
    def __init__(self, nature, kind):
        super().__init__(nature)
        self.kind = kind
 
    def get_kind(self):
        print('Kind:', self.kind)
 
class GrandChild(Child):
    def __init__(self, nature, kind, behavior):
        super().__init__(nature, kind)
        self.behavior = behavior
 
    def get_behavior(self):
        print('Behavior:', self.behavior)
 
grandchild1 = GrandChild('Good', 'Good', 'Good')
grandchild1.get_nature()
grandchild1.get_kind()
grandchild1.get_behavior()

Output:

command
C:\Users\username>python multilevel_inheritance.py
Nature: Good
Kind: Good
Behavior: Good
command
C:\Users\username>python multilevel_inheritance.py
Nature: Good
Kind: Good
Behavior: Good

In the above example, we have created three classes named FatherFather, ChildChild, and GrandChildGrandChild. The ChildChild class is derived from the FatherFather class. The GrandChildGrandChild class is derived from the ChildChild class. The FatherFather class is the superclass of the ChildChild class. The ChildChild class is the superclass of the GrandChildGrandChild class. The GrandChildGrandChild class inherits the features of the FatherFather and ChildChild classes. The FatherFather class has an instance variable named naturenature. The ChildChild class has an instance variable named kindkind. The GrandChildGrandChild class has an instance variable named behaviorbehavior. The FatherFather class has a method named get_nature()get_nature() that prints the naturenature variable. The ChildChild class has a method named get_kind()get_kind() that prints the kindkind variable. The GrandChildGrandChild class has a method named get_behavior()get_behavior() that prints the behaviorbehavior variable. The ChildChild class has a constructor that takes two parameters naturenature and kindkind. The GrandChildGrandChild class has a constructor that takes three parameters naturenature, kindkind, and behaviorbehavior. The super().__init__(nature)super().__init__(nature) statement is used to call the constructor of the FatherFather class. The super().__init__(nature, kind)super().__init__(nature, kind) statement is used to call the constructor of the ChildChild class.

Hierarchical Inheritance

In hierarchical inheritance, a class is allowed to inherit from more than one derived class. It is the process of deriving a new class from already derived class. Let’s see an example of hierarchical inheritance.

Diagrammatic Representation of Hierarchical Inheritance

Hierarchical Inheritance in Python


  classDiagram
    Animal <|-- Manmal
    Animal <|-- Bird
    Animal <|-- Dog
    Animal <|-- Bat
    Dog <|-- BabyDog
    Bird <|-- Parrot
    Animal : +void speak()
    Manmal : +void giveBirth()
    Bird : +void fly()
    Dog : +void bark()
    Bat : +void sonar()
    BabyDog : +void crawl()
    Parrot : +void talk()

Hierarchical Inheritance

hierarchical_inheritance.py
class Animal:
    def speak(self):
        print('Speaking')
 
class Mammal(Animal):
    def giveBirth(self):
        print('Giving Birth')
 
class Bird(Animal):
    def fly(self):
        print('Flying')
 
class Dog(Animal):
    def bark(self):
        print('Barking')
 
class Bat(Animal):
    def sonar(self):
        print('Using Sonar')
 
class BabyDog(Dog):
    def crawl(self):
        print('Crawling')
 
class Parrot(Bird):
    def talk(self):
        print('Talking')
 
dog1 = Dog()
dog1.speak()
dog1.bark()
babydog1 = BabyDog()
babydog1.speak()
babydog1.bark()
babydog1.crawl()
parrot1 = Parrot()
parrot1.speak()
parrot1.fly()
parrot1.talk()
hierarchical_inheritance.py
class Animal:
    def speak(self):
        print('Speaking')
 
class Mammal(Animal):
    def giveBirth(self):
        print('Giving Birth')
 
class Bird(Animal):
    def fly(self):
        print('Flying')
 
class Dog(Animal):
    def bark(self):
        print('Barking')
 
class Bat(Animal):
    def sonar(self):
        print('Using Sonar')
 
class BabyDog(Dog):
    def crawl(self):
        print('Crawling')
 
class Parrot(Bird):
    def talk(self):
        print('Talking')
 
dog1 = Dog()
dog1.speak()
dog1.bark()
babydog1 = BabyDog()
babydog1.speak()
babydog1.bark()
babydog1.crawl()
parrot1 = Parrot()
parrot1.speak()
parrot1.fly()
parrot1.talk()

Output:

command
C:\Users\username>python hierarchical_inheritance.py
Speaking
Barking
Speaking
Barking
Crawling
Speaking
Flying
Talking
command
C:\Users\username>python hierarchical_inheritance.py
Speaking
Barking
Speaking
Barking
Crawling
Speaking
Flying
Talking

In this example, we have created seven classes named AnimalAnimal, MammalMammal, BirdBird, DogDog, BatBat, BabyDogBabyDog, and ParrotParrot. The MammalMammal, BirdBird, DogDog, BatBat, BabyDogBabyDog, and ParrotParrot classes are derived from the AnimalAnimal class. The AnimalAnimal class is the superclass of the MammalMammal, BirdBird, DogDog, BatBat, BabyDogBabyDog, and ParrotParrot classes. The MammalMammal class is the superclass of the DogDog and BatBat classes. The BirdBird class is the superclass of the ParrotParrot class. The DogDog class is the superclass of the BabyDogBabyDog class. The MammalMammal class has a method named giveBirth()giveBirth() that prints Giving BirthGiving Birth. The BirdBird class has a method named fly()fly() that prints FlyingFlying. The DogDog class has a method named bark()bark() that prints BarkingBarking. The BatBat class has a method named sonar()sonar() that prints Using SonarUsing Sonar. The BabyDogBabyDog class has a method named crawl()crawl() that prints CrawlingCrawling. The ParrotParrot class has a method named talk()talk() that prints TalkingTalking. The AnimalAnimal class has a method named speak()speak() that prints SpeakingSpeaking. The DogDog class has a constructor that takes no parameters. The BabyDogBabyDog class has a constructor that takes no parameters. The ParrotParrot class has a constructor that takes no parameters. The dog1dog1 object is created using the DogDog class. The dog1.speak()dog1.speak() statement calls the speak()speak() method of the AnimalAnimal class. The dog1.bark()dog1.bark() statement calls the bark()bark() method of the DogDog class. The babydog1babydog1 object is created using the BabyDogBabyDog class. The babydog1.speak()babydog1.speak() statement calls the speak()speak() method of the AnimalAnimal class. The babydog1.bark()babydog1.bark() statement calls the bark()bark() method of the DogDog class. The babydog1.crawl()babydog1.crawl() statement calls the crawl()crawl() method of the BabyDogBabyDog class. The parrot1parrot1 object is created using the ParrotParrot class. The parrot1.speak()parrot1.speak()

Hybrid Inheritance

In hybrid inheritance, when multiple types of inheritance are combined together. It is the process of deriving a new class from already derived class. Let’s see an example of hybrid inheritance.

Diagrammatic Representation of Hybrid Inheritance

Hybrid Inheritance in Python


  classDiagram
    Car --|> Vehicle
    Car --|> SportsCar
    SportsCar --|> Ferrari
    Car : +void drive()
    Vehicle : +void run()
    Ferrari : +void use()
    SportsCar : +void race()

Hybrid Inheritance

hybrid_inheritance.py
class Vehicle:
    def run(self):
        print('Running')
 
class Car(Vehicle):
    def drive(self):
        print('Driving')
 
class SportsCar(Vehicle):
    def race(self):
        print('Racing')
 
class Ferrari(Car, SportsCar):
    def use(self):
        print('Using')
 
ferrari1 = Ferrari()
ferrari1.run()
ferrari1.drive()
ferrari1.use()
hybrid_inheritance.py
class Vehicle:
    def run(self):
        print('Running')
 
class Car(Vehicle):
    def drive(self):
        print('Driving')
 
class SportsCar(Vehicle):
    def race(self):
        print('Racing')
 
class Ferrari(Car, SportsCar):
    def use(self):
        print('Using')
 
ferrari1 = Ferrari()
ferrari1.run()
ferrari1.drive()
ferrari1.use()

Output:

command
C:\Users\username>python hybrid_inheritance.py
Running
Driving
Using
command
C:\Users\username>python hybrid_inheritance.py
Running
Driving
Using

In this example, we have created four classes named VehicleVehicle, CarCar, SportsCarSportsCar, and FerrariFerrari. The CarCar and SportsCarSportsCar classes are derived from the VehicleVehicle class. The FerrariFerrari class is derived from the CarCar and SportsCarSportsCar classes. The VehicleVehicle class is the superclass of the CarCar and SportsCarSportsCar classes. The CarCar class is the superclass of the FerrariFerrari class. The SportsCarSportsCar class is the superclass of the FerrariFerrari class. The VehicleVehicle class has a method named run()run() that prints RunningRunning. The CarCar class has a method named drive()drive() that prints DrivingDriving. The SportsCarSportsCar class has a method named race()race() that prints RacingRacing. The FerrariFerrari class has a method named use()use() that prints UsingUsing. The ferrari1ferrari1 object is created using the FerrariFerrari class. The ferrari1.run()ferrari1.run() statement calls the run()run() method of the VehicleVehicle class. The ferrari1.drive()ferrari1.drive() statement calls the drive()drive() method of the CarCar class. The ferrari1.use()ferrari1.use() statement calls the use()use() method of the FerrariFerrari class.

Advantages of Inheritance

  1. Code Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
  2. Extensibility: Inheritance is used to add new features to an existing class without modifying it. This is useful when we have to add new features to an existing application that we don’t want to modify.
  3. Data Hiding: Inheritance is used to hide the data of a class from other classes. This is useful when we want to hide the internal representation of an object from the outside world.
  4. Overriding Methods: Inheritance is used to override the methods of the superclass in the subclass. This is useful when we want to change the behavior of a method in the subclass.
  5. Polymorphism: Inheritance is used to achieve polymorphism. Polymorphism means the ability to take various forms. In Python, we can use the same method name in the child class as defined in the parent class. This is useful when we want to perform a single action in different ways.
  6. Flexibility: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  7. Simplicity: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  8. Modularity: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  9. Modifiability: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  10. Maintainability: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.

Disadvantages of Inheritance

  1. Complexity: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  2. Tight Coupling: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  3. Fragility: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  4. Immobility: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.
  5. Impermanence: Inheritance is used to make a single class that can be used for different purposes. This is useful when we want to create a class that can be used for different purposes.

Conclusion

In this tutorial, we have learned about Inheritance in Python. Inheritance is a way of creating a new class for using details of an existing class without modifying it. In this tutorial, we have learned about Inheritance in Python with examples. We have also learned about the types of Inheritance in Python. In the next tutorial, we will learn about Polymorphism in Python. For more information on Inheritance, you can refer to the official documentation. For more tutorials on Python, you can visit Python Central Hub.

Was this page helpful?

Let us know how we did