Polymorphism

Polymorphism in Python: The word Polymorphism sounds fancy, but it just means "Many Shapes." Imagine you have a "Remote Control" with a button labeled "Power."…

Concept Explanation

The word Polymorphism sounds fancy, but it just means "Many Shapes."

Imagine you have a "Remote Control" with a button labeled "Power." If you point it at a TV, the button turns the TV on. If you point it at an Air Conditioner, the same button turns the AC on. Even though the action (Power On) is the same, how the machine performs that action is different.

In Python, Polymorphism allows different classes to have methods with the same name, performing different actions depending on which object is using them.


Syntax or Core Structure

Polymorphism through Methods

Multiple classes can have a method called speak(), but the result is different.

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

class Dog:
    def speak(self):
        print("Woof!")

# Both objects can be used in the exact same loop
animals = [Cat(), Dog()]

for a in animals:
    a.speak() # Output: Meow! then Woof!

Code Example #1 (Basic)

Polymorphism with geometric shapes. Both have an area() method, but use different math.

import math

class Circle:
    def __init__(self, radius):
        self.r = radius
    def area(self):
        return math.pi * self.r**2

class Square:
    def __init__(self, side):
        self.s = side
    def area(self):
        return self.s**2

shapes = [Circle(10), Square(5)]

for s in shapes:
    print(f"Area: {s.area():.2f}")

Code Example #2 (Intermediate)

Using Polymorphism with Inheritance. This is how most real software is built—defining a base "interface" that children fulfill.

class File:
    def open(self):
        raise NotImplementedError("Subclass must implement this!")

class TextFile(File):
    def open(self):
        print("Opening text file in Notepad...")

class ImageFile(File):
    def open(self):
        print("Opening image in Photo Viewer...")

def process_file(file_obj):
    # This function doesn't care what TYPE of file it is,
    # as long as it has an .open() method!
    file_obj.open()

process_file(TextFile())
process_file(ImageFile())

Real World Example

Think of a "Payment Processor" in an app. You might want to pay with a Credit Card, PayPal, or Crypto. Each one has a pay() method.

# 💳 Payment System
class CreditCard:
    def pay(self, amount):
        print(f"Charging ${amount} to your Credit Card.")

class PayPal:
    def pay(self, amount):
        print(f"Connecting to PayPal to send ${amount}...")

# The "Checkout" logic is clean and simple!
def checkout(payment_method, total):
    payment_method.pay(total)

checkout(CreditCard(), 150)
checkout(PayPal(), 50)

Common Mistakes

  1. Method Name Mismatch: If you call one method speak() and the other make_sound(), you lose polymorphism. You have to call them different things in your loops.
  2. Assuming Type: If you write code that only works for a List, your program will crash if someone sends it a Set. Polymorphism encourages you to write code that works on behavior (can I loop over this?), not type (is this a list?).

Best Practices

  • Consistent Naming: Use clear, shared names for shared actions. save(), load(), render() are great polymorphic method names.
  • Interface Definition: Define a parent class with the "expected" methods so other developers know what to implement in their child classes.

Practice Exercises

  1. The Transport Lesson: Create two classes, Boat and Plane. Give both a move() method. The boat should say "I am sailing" and the plane should say "I am flying." Loop through them.
  2. Area Extension: Add a Rectangle class to the geometric shape example above. It should take width and height and return the area.
  3. The Volume Controller: Create classes for Radio and TV. Both should have a volume_up() method that increments a counter.