fbpx

Inheritance and Polymorphism in Python

1. Inheritance:

Inheritance is a fundamental concept in Object-Oriented Programming that allows a new class (subclass or derived class) to inherit attributes and methods from an existing class (base class or parent class). This promotes code reuse and enables the creation of a hierarchy of classes.

1.1 Syntax:

class BaseClass:
    # Base class attributes and methods

class SubClass(BaseClass):
    # Subclass attributes and methods, inherits from BaseClass

1.2 Example:

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

    def speak(self):
        raise NotImplementedError("Subclasses must implement the speak method")

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Using the subclasses
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!

2. Polymorphism:

Polymorphism allows objects of different classes to be treated as objects of a common base class. This enables flexibility and dynamic behavior in your code.

2.1 Method Overriding:

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.

class Shape:
    def area(self):
        raise NotImplementedError("Subclasses must implement the area method")

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

# Using polymorphism
circle = Circle(5)
rectangle = Rectangle(4, 6)

print(circle.area())      # Output: 78.5
print(rectangle.area())   # Output: 24

2.2 Function Polymorphism:

Functions can also exhibit polymorphic behavior based on the types of arguments they receive.

def introduce(animal):
    print(f"This is {animal.name}.")

# Using polymorphism with different types of animals
introduce(dog)   # Output: This is Buddy.
introduce(cat)   # Output: This is Whiskers.

3. Abstract Base Classes (ABC):

Abstract Base Classes are used to define abstract methods in a base class that must be implemented by its subclasses.

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

4. Conclusion:

Inheritance and polymorphism are powerful concepts that enhance code organization, flexibility, and reusability in Object-Oriented Programming. By leveraging these principles, you can create a hierarchy of classes, promote code reuse, and achieve dynamic behavior in your Python programs.

In the next sections, we’ll explore more advanced topics and practical applications of these concepts in Python.