What Are Python Inheritance and Polymorphism? See Examples

Inheritance and polymorphism are key concepts in object-oriented programming (OOP) in Python.

  • Inheritance allows a class (child) to inherit attributes and methods from another class (parent), promoting code reuse.
  • Polymorphism allows objects of different classes to be used interchangeably, enabling flexible and scalable code.

Why Inheritance and Polymorphism Are Important

  • Reduces code duplication
  • Promotes modular design
  • Makes programs easier to maintain
  • Enables real-world modeling of objects

1. Python Inheritance

Inheritance allows a child class to inherit from a parent class using ParentClass in parentheses.

# Parent class
class Animal:
    def speak(self):
        print("Some sound")

# Child class
class Dog(Animal):
    def speak(self):
        print("Bark")

# Create objects
animal = Animal()
dog = Dog()

animal.speak()  # Output: Some sound
dog.speak()     # Output: Bark

Types of Inheritance

  1. Single Inheritance – One parent, one child
  2. Multiple Inheritance – Multiple parents
  3. Multilevel Inheritance – Grandparent → Parent → Child
  4. Hierarchical Inheritance – One parent, multiple children

2. Python Polymorphism

Polymorphism allows different objects to respond to the same method in different ways.

Example with Method Overriding

class Cat(Animal):
    def speak(self):
        print("Meow")

def make_sound(animal):
    animal.speak()

make_sound(Dog())  # Bark
make_sound(Cat())  # Meow

Here, the same make_sound() function works for multiple types of objects.


Example with Operator Overloading

a = 5
b = 3
print(a + b)  # 8 (int addition)

x = "Hello"
y = "World"
print(x + y)  # HelloWorld (string concatenation)

Python uses polymorphism to handle different data types with the same operator.


Best Practices

✔ Use inheritance only when there is a clear “is-a” relationship
✔ Avoid deep inheritance hierarchies
✔ Use polymorphism for flexible and reusable code
✔ Keep method overriding consistent with parent method signature


Conclusion

Inheritance and polymorphism are powerful OOP concepts in Python. They help in creating reusable, modular, and scalable programs that model real-world problems efficiently.


References

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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