The Power of Inheritance OOPs: Python Perspective

Inheritance is a core principle in OOPs (Object-Oriented Programming) that enables a child class or derived class to inherit properties and methods from a parent class or bass class. This greatly encourages code reuse and creates a hierarchical structure among classes.

Key Concepts of Inheritance

  1. Base Class (Parent Class): The class whose properties and methods are inherited.
  2. Derived Class (Child Class): The class that inherits from the base class.
  3. Method Overriding: A child class can provide a specific implementation of a method that is already defined in its parent class.
  4. Multiple Inheritance: A derived class can inherit from multiple base classes.

Types of Inheritance

TypeDescription
Single InheritanceA derived class inherits from a single base class.
Multiple InheritanceA derived class inherits from multiple base classes.
Multilevel InheritanceA derived class is created from another derived class.
Hierarchical InheritanceMultiple derived classes inherit from a single base class.
Hybrid InheritanceA combination of two or more types of inheritance.
image 3 Explore and Read Our Blogs Written By Our Insutry Experts Learn From KSR Data Vizon

Basic Syntax of Inheritance

class Parent:
    def __init__(self):
        print("Parent class constructor")

    def parent_method(self):
        print("This is a method from the Parent class")

class Child(Parent):
    def __init__(self):
        super().__init__()  # Call the constructor of Parent class
        print("Child class constructor")

    def child_method(self):
        print("This is a method from the Child class")

# Create an instance of the Child class
child_instance = Child()
child_instance.parent_method()  # Call method from Parent class
child_instance.child_method()    # Call method from Child class

Different Types of Inheritance

1. Single Inheritance

Single inheritance allows a sub-class to inherit properties from a single superclass, enabling access to both parent and child class properties, with parent class properties automatically available to the child class

class Animal:
    def speak(self):
        return "Animal speaks"

class Dog(Animal):
    def bark(self):
        return "Dog barks"

dog = Dog()
print(dog.speak())  # Output: Animal speaks
print(dog.bark())   # Output: Dog barks

2. Multiple Inheritance

It enables a sub-class to inherit properties or attributes from multiple super classes, allowing access to properties from all parent classes while ensuring that conflicts are resolved according to the method resolution order (MRO).

class Flyer:
    def fly(self):
        return "Can fly"

class Swimmer:
    def swim(self):
        return "Can swim"

class Duck(Flyer, Swimmer):
    def quack(self):
        return "Duck quacks"

duck = Duck()
print(duck.fly())   # Output: Can fly
print(duck.swim())  # Output: Can swim
print(duck.quack()) # Output: Duck quacks

3. Multilevel Inheritance

It allows a sub-class to inherit from another sub-class, creating a hierarchy of classes where each level can access properties from its parent class, facilitating a a well-structured relationship among multiple classes.

class Grandparent:
    def grandparent_method(self):
        return "Method from Grandparent"

class Parent(Grandparent):
    def parent_method(self):
        return "Method from Parent"

class Child(Parent):
    def child_method(self):
        return "Method from Child"

child = Child()
print(child.grandparent_method())  # Output: Method from Grandparent
print(child.parent_method())        # Output: Method from Parent
print(child.child_method())         # Output: Method from Child

4. Hierarchical Inheritance

It involves multiple sub-classes inheriting from a single superclass, allowing each subclass to access the properties of the shared parent class while maintaining their unique characteristics.

class Parent:
    def parent_method(self):
        return "Method from Parent"

class Child1(Parent):
    def child1_method(self):
        return "Method from Child 1"

class Child2(Parent):
    def child2_method(self):
        return "Method from Child 2"

child1 = Child1()
child2 = Child2()
print(child1.parent_method())  # Output: Method from Parent
print(child2.parent_method())  # Output: Method from Parent

5. Hybrid Inheritance

Hybrid inheritance combines multiple inheritance types, where a subclass can inherit from more than one superclass and can also participate in multilevel or hierarchical inheritance, allowing for a flexible and complex class structure while managing potential conflicts through method resolution order (MRO).

# Base class
class Animal:
    def speak(self):
        return "Animal speaks"

# Derived class 1
class Bird(Animal):
    def fly(self):
        return "Bird can fly"

# Derived class 2
class Fish(Animal):
    def swim(self):
        return "Fish can swim"

# Derived class 3 (Hybrid class)
class Duck(Bird, Fish):
    def quack(self):
        return "Duck quacks"

# Create an instance of Duck
duck = Duck()

# Access methods from the base and derived classes
print(duck.speak())  # Output: Animal speaks
print(duck.fly())    # Output: Bird can fly
print(duck.swim())   # Output: Fish can swim
print(duck.quack())  # Output: Duck quacks

super() Method:

The super() method allows a sub-class to access methods or actions of its parent class. It is most commonly used to call the constructor (__init__) of a parent class or other methods within that class, allowing code reusability, and maintainability, and ensuring that the base class’s functionality is properly incorporated into the subclass.

Why Use super()?

  1. Inheritance and Method Resolution Order (MRO): super() helps manage the method resolution order in multiple inheritance, ensuring that the correct method is invoked from the right class.
  2. Code Reusability: It allows the child class to reuse code from the parent class without explicitly referencing the parent class by name.
  3. Maintainability: If the parent class name changes, you don’t have to change the child class’s super() calls.

Syntax:

super().method_name(args)
  • method_name: The method from the parent class that you want to call.
  • args: Arguments that are passed to the method.

Example:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def sound(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def __init__(self, name, breed):
        # Call the parent class's __init__ method using super()
        super().__init__(name)
        self.breed = breed
    
    def sound(self):
        # Call the parent class's sound method using super()
        super().sound()
        print(f"{self.name} is a {self.breed} and barks")
        
# Create an instance of Dog
dog = Dog("Buddy", "Golden Retriever")
dog.sound()

# Output:
Buddy makes a sound
Buddy is a Golden Retriever and barks

In the Dog class, super() is utilized to invoke the __init__ and sound methods from the parent class Animal, preserving the base functionality while introducing Dog-specific behavior

Conclusion

Inheritance in Python enables the formation of a class hierarchy, encouraging code reuse and minimizing redundancy. By utilizing inheritance, developers can craft more structured and modular code

Knowledge Check

Related Article No.4

https://blog.ksrdatavision.com/python/input-and-output-in-python
Data Analytics with Power Bi and Fabric
Could Data Engineer
Data Analytics With Power Bi Fabic
AWS Data Engineering with Snowflake
Azure Data Engineering
Azure & Fabric for Power bi
Full Stack Power Bi
Subscribe to our channel & Don’t miss any update on trending technologies

Kick Start Your Career With Our Data Job

Master Fullstack Power BI – SQL, Power BI, Azure Cloud & Fabric Tools
Master in Data Science With Generative AI Transform Data into Business Solutions
Master Azure Data Engineering – Build Scalable Solutions for Big Data
Master AWS Data Engineering with Snowflake: Build Scalable Data Solutions
Transform Your Productivity With Low Code Technology: Master the Microsoft Power Platform

Social Media channels

► KSR Datavizon Website :- https://www.datavizon.com
► KSR Datavizon LinkedIn :- https://www.linkedin.com/company/datavizon/
► KSR Datavizon You tube :- https://www.youtube.com/c/KSRDatavizon
► KSR Datavizon Twitter :- https://twitter.com/ksrdatavizo

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *