SwadhyAI Notes

All Python notes

Python Polymorphism 🎭

Many Forms

The word "polymorphism" means "many forms". In programming, it refers to methods, functions, or operators with the same name that can be executed on many objects or classes.

✨ Function Polymorphism

An example of a Python function that can be used on different objects is the len() function.

python
# String
print(len("Hello")) # 5

# List
print(len(["a", "b", "c"])) # 3

# Dictionary
print(len({"brand": "Ford", "model": "Mustang"})) # 2

🏗️ Class Polymorphism

Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.

python
class Car:
  def move(self):
    print("Drive!")

class Boat:
  def move(self):
    print("Sail!")

class Plane:
  def move(self):
    print("Fly!")

# Different objects, same method name
car1 = Car()
boat1 = Boat()
plane1 = Plane()

for x in (car1, boat1, plane1):
  x.move()

🦆 Duck Typing

Python uses "Duck Typing": "If it walks like a duck and quacks like a duck, then it must be a duck." Use this principle to write flexible code that accepts any object as long as it has the required methods.

python
def make_it_move(vehicle):
    vehicle.move()

# Works with any object that has a .move() method
make_it_move(car1)
make_it_move(boat1)

✨ Pro Tip: Inheritance Polymorphism

If child classes inherit from a parent class, they can override methods. This allows you to treat all child objects as instances of the parent class, while still executing their specific method implementations.