Lesson 4

Introduction to Polymorphism in Python

Introduction to Polymorphism

Welcome back! We're continuing our journey into object-oriented programming (OOP) with a new and exciting topic: Polymorphism. You've already learned about classes, objects, and inheritance, which are essential building blocks of OOP. Now, it's time to explore how polymorphism can make your code more flexible and reusable.

Understanding Polymorphism

Polymorphism in Python allows you to call derived class methods through a base class reference. This can make your code more dynamic and general. Essentially, polymorphism enables methods to do different things based on the object it is acting upon, even if they share the same name.

When a method in a derived class has the same name as a method in its base class, the derived class method overrides the method in the base class. This ensures that the call to the method runs the derived class's version of the method, allowing the same method call to perform different tasks depending on the object it is acting upon.

Method Overriding

As we briefly touched on in the previous lesson, method overriding occurs when a derived class provides a specific implementation of a method that is already defined in its base class. The method in the derived class overrides the corresponding method in the base class.

This allows the derived class to offer a specific behavior while still maintaining the same method signature. Imagine different animals like birds, fish, and dogs. Each animal can eat(), move(), and speak(). Even though these actions have the same name for each animal, the implementation for eating, moving, and speaking can vary:

  • Bird: Moving might involve flying.
  • Fish: Moving might involve swimming.
  • Dog: Moving might involve running.

Despite these differences, a single interface (move() method) allows us to handle all animal types polymorphically.

Here’s an example:

Python
1class Animal: 2 def speak(self): 3 print("Animal speaks") 4 5class Dog(Animal): 6 def speak(self): 7 print("Dog barks") 8 9if __name__ == "__main__": 10 generic_animal = Animal() 11 generic_animal.speak() # Output: Animal speaks 12 13 dog = Dog() 14 dog.speak() # Output: Dog barks

In this snippet, the Dog class overrides the speak method of the Animal class. When the speak method is called on an instance of Dog, the overridden method in Dog is executed instead of the method in Animal. In contrast to the previous lesson's example, we do not call super().speak() here because we intend to completely override the method from the parent class.

Updated Example with Polymorphism:

Let's expand our initial Person, Student, and Teacher example to include a function that can accept any Person object and demonstrate polymorphism:

Python
1class Person: 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 6 def display(self): 7 print(f"Name: {self.name}, Age: {self.age}") 8 9class Student(Person): 10 def __init__(self, name, age, major): 11 super().__init__(name, age) 12 self.major = major 13 14 def display(self): 15 super().display() 16 print(f"Major: {self.major}") 17 18class Teacher(Person): 19 def __init__(self, name, age, subject): 20 super().__init__(name, age) 21 self.subject = subject 22 23 def display(self): 24 super().display() 25 print(f"Subject: {self.subject}") 26 27def show_person_info(person): 28 person.display() 29 30if __name__ == "__main__": 31 student = Student("Alice", 30, "Computer Science") 32 teacher = Teacher("Bob", 25, "Mathematics") 33 34 show_person_info(student) 35 # Output: 36 # Name: Alice, Age: 30 37 # Major: Computer Science 38 39 show_person_info(teacher) 40 # Output: 41 # Name: Bob, Age: 25 42 # Subject: Mathematics

In this updated example, we defined a function show_person_info that takes an instance of Person as a parameter. This function calls the display method on the person parameter. Thanks to polymorphism, this function can accept both Student and Teacher objects (which are derived from Person). When show_person_info is called with a Student or Teacher object, the appropriate display method defined in the derived class is executed, demonstrating polymorphism in action.

Conclusion

Polymorphism is a crucial concept in object-oriented programming because it brings flexibility and scalability to your code.

By allowing functions to operate on different types through a common interface, polymorphism enhances your code's flexibility and promotes code reusability, making it easier to extend and reuse your work.

Additionally, polymorphism simplifies code management by handling similar operations in a unified manner, making your codebase easier to maintain and expand.

Ready to dive into the practice section and see polymorphism in action? Let's get started!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.