Skip to Content
Course content

5.3 Inheritance and Polymorphism

Inheritance and Polymorphism are two of the most important concepts in Object-Oriented Programming (OOP). They allow for creating flexible, reusable, and easily maintainable code. Below is an explanation of both concepts in Python.

Inheritance

Inheritance allows a class (called a child class or subclass) to inherit properties and methods from another class (called a parent class or superclass). The subclass can access and modify the attributes and methods of the parent class, allowing code reuse and the creation of more specialized classes.

How Inheritance Works:

  • The child class inherits attributes and methods from the parent class.
  • The child class can extend or modify the functionality of the parent class.

Syntax for Inheritance:

class ParentClass:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"Hello, my name is {self.name}.")

class ChildClass(ParentClass):
    def __init__(self, name, age):
        # Inherit the __init__ method of ParentClass
        super().__init__(name)
        self.age = age

    def speak(self):
        # Overriding the parent method
        print(f"Hi, I am {self.name} and I am {self.age} years old.")

# Creating instances
parent = ParentClass("John")
child = ChildClass("Mike", 25)

parent.speak()  # Output: Hello, my name is John.
child.speak()   # Output: Hi, I am Mike and I am 25 years old.
  • Inheritance: The ChildClass inherits from ParentClass. This allows it to use the speak() method from ParentClass but also modify it as needed (this is called method overriding).
  • super(): The super() function is used to call the constructor (__init__) of the parent class to initialize the inherited properties.

Types of Inheritance in Python:

  1. Single Inheritance: A subclass inherits from a single parent class.
  2. Multiple Inheritance: A subclass inherits from multiple parent classes.
  3. Multilevel Inheritance: A subclass inherits from a parent class, which in turn inherits from another parent class.
  4. Hierarchical Inheritance: Multiple subclasses inherit from a single parent class.

Polymorphism

Polymorphism means "many forms" and refers to the ability of an object to take many forms. In the context of OOP, it allows methods to do different things depending on the object they are acting upon. There are two main types of polymorphism in Python: method overriding (runtime polymorphism) and method overloading (though Python supports overriding but not method overloading).

Polymorphism through Method Overriding:

Polymorphism is achieved through method overriding. This is when a method in a subclass has the same name as a method in the parent class, but the implementation in the subclass is different.

Example of Polymorphism through Method Overriding:
class Animal:
    def sound(self):
        print("Some animal sound")

class Dog(Animal):
    def sound(self):
        print("Woof!")

class Cat(Animal):
    def sound(self):
        print("Meow!")

# Creating instances of Dog and Cat
dog = Dog()
cat = Cat()

# Polymorphism in action
dog.sound()  # Output: Woof!
cat.sound()  # Output: Meow!
  • Polymorphism: Both Dog and Cat are subclasses of Animal and override the sound() method. Even though the sound() method is called in both cases, the output differs depending on the object (dog or cat).

Polymorphism through Duck Typing:

Python is dynamically typed, meaning that the type of an object is determined at runtime. This allows for duck typing, where if an object implements a method or behavior that is required, it can be used interchangeably, even if the object is of a different class.

Example of Duck Typing:
class Bird:
    def fly(self):
        print("Flying in the sky!")

class Airplane:
    def fly(self):
        print("Flying in the air at high speed!")

def make_it_fly(flyable_object):
    flyable_object.fly()

# Creating instances of Bird and Airplane
bird = Bird()
airplane = Airplane()

make_it_fly(bird)      # Output: Flying in the sky!
make_it_fly(airplane)  # Output: Flying in the air at high speed!
  • Duck Typing: Even though Bird and Airplane are different classes, both have a fly() method. As long as an object has the method fly(), it can be passed to the make_it_fly() function.

Advantages of Inheritance and Polymorphism:

  1. Code Reusability: Inheritance allows the reuse of existing code, which reduces redundancy and enhances maintainability.
  2. Extensibility: You can add new functionality by simply extending the parent class, without altering existing code.
  3. Flexibility and Maintainability: Polymorphism makes the code more flexible and easy to maintain. It enables you to write code that can work with different types of objects.
  4. Simplified Code: By overriding methods and using polymorphism, you can write cleaner, more concise, and more readable code.

Key Differences between Inheritance and Polymorphism:

Concept Inheritance Polymorphism
Definition Inheritance is the mechanism of acquiring properties and behaviors from a parent class. Polymorphism allows methods to behave differently based on the object type.
Purpose To enable code reuse and create a relationship between classes. To allow different classes to be treated as the same type via method overriding.
Usage Creates hierarchical relationships between classes. Enables different classes to provide different implementations of the same method.
Example A Dog class inheriting from the Animal class. A Dog and Cat class providing different implementations of the sound() method.

Conclusion:

  • Inheritance helps in organizing code into a hierarchy and promotes code reuse by inheriting attributes and methods from a parent class.
  • Polymorphism makes it possible for different objects to share the same interface (method name) but perform different behaviors based on their type or class.

Together, inheritance and polymorphism enable the creation of modular, flexible, and maintainable object-oriented code.

Commenting is not enabled on this course.