Polymorphism

What You'll Learn: In this tutorial, you'll discover how polymorphism works in Python. Polymorphism allows methods/functions/operators with the same name to be executed on many objects or classes, making code more flexible and reusable.

Function Polymorphism

The len() function is an example of polymorphism in Python, as it can be used on different objects.

For Strings: len() returns the number of characters in a string.

Example Code:

python
x = "Hello World!"
print(len(x))

Output:

 
12

For Tuples: len() returns the number of items in a tuple.

Example Code:

python
mytuple = ("apple", "banana", "cherry")
print(len(mytuple))

Output:

 
3

For Dictionaries: len() returns the number of key-value pairs in a dictionary.

Example Code:

python
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(len(thisdict))

Output:

 
3

Class Polymorphism

Polymorphism is often used in class methods, where multiple classes have the same method name.

Example Code:

python
class Car:
  def move(self):
    print("Drive!")
class Boat:
  def move(self):
    print("Sail!")
class Plane:
  def move(self):
    print("Fly!")
car1 = Car()
boat1 = Boat()
plane1 = Plane()
for x in (car1, boat1, plane1):
  x.move()

Output:

 
Drive!
Sail!
Fly!

Inheritance Class Polymorphism

Classes with child classes can use polymorphism. A parent class can have methods that child classes inherit and potentially override.

Example Code:

python
class Vehicle:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model
  def move(self):
    print("Move!")
class Car(Vehicle):
  pass
class Boat(Vehicle):
  def move(self):
    print("Sail!")
class Plane(Vehicle):
  def move(self):
    print("Fly!")
car1 = Car("Ford", "Mustang")
boat1 = Boat("Ibiza", "Touring 20")
plane1 = Plane("Boeing", "747")
for x in (car1, boat1, plane1):
  print(x.brand)
  print(x.model)
  x.move()

Output:

 
Ford
Mustang
Move!
Ibiza
Touring 20
Sail!
Boeing
747
Fly!

Try It Yourself: Fun Exercises

  1. Animal Sounds:
    • Create a parent class Animal with a method sound().
    • Create child classes Dog, Cat, and Bird, each overriding the sound() method to print different sounds.
  2. Shape Area Calculation:
    • Create a parent class Shape with a method area().
    • Create child classes Square, Rectangle, and Circle, each overriding the area() method to calculate and print their areas.

Summary:

In this Python tutorial, we learned about polymorphism, which allows methods to work on different objects or classes. We explored function polymorphism using the len() function, class polymorphism with different classes having the same method, and inheritance class polymorphism where child classes inherit and override parent methods. Keep experimenting and have fun with polymorphism in Python!