Python Polymorphism

JK1982 
Created at
Updated at  

  6,947   0   0  

The word "polymorphism" means "many forms", and in programming it refers to methods/functions/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.


String

For strings len() returns the number of characters:

x = "Hello World!"

print(len(x))

Tuple

For tuples len() returns the number of items in the tuple:

mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

Dictionary

For dictionaries len() returns the number of key/value pairs in the dictionary:

thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}

print(len(thisdict))

Class Polymorphism

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

For example, say we have three classes: Car, Boat, and Plane, and they all have a method called move():

class Car:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

  def move(self):
    print("Drive!")

class Boat:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

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

class Plane:
  def __init__(self, brand, model):
    self.brand = brand
    self.model = model

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

car1 = Car("Ford", "Mustang")       #Create a Car class
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747")     #Create a Plane class

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

Look at the for loop at the end. Because of polymorphism we can execute the same method for all three classes.


Inheritance Class Polymorphism

What about classes with child classes with the same name? Can we use polymorphism there?

Yes. If we use the example above and make a parent class called Vehicle, and make Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle methods, but can override them:

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") #Create a Car object
boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object

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

Child classes inherits the properties and methods from the parent class.

In the example above you can see that the Car class is empty, but it inherits brand, model, and move() from Vehicle.

The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both override the move() method.

Because of polymorphism we can execute the same method for all classes.



Tags: Python Python Polymorphism Share on Facebook Share on X

◀ PREVIOUS
Python Iterators

▶ NEXT
Python Scope

  Comments 0
SIMILAR POSTS

Python Scope

(updated at )

Python Modules

(updated at )

Python Iterators

(updated at )

Python Inheritance

(updated at )

Python Classes/Objects

(updated at )

Python Arrays

(updated at )

Python Lambda

(updated at )

Python Functions

(updated at )

Python While Loops/For Loops

(updated at )

Python Conditions and If statements

(updated at )

Python Dictionaries

(updated at )

Python Sets

(updated at )

Python Tuples

(updated at )

Python Comparison Operators

(updated at )

Python Arithmetic Operators

(created at )

Printing string n times

(created at )

String concatenation by join()

(created at )

Python Lists

(updated at )

Python String Operations

(updated at )

Python Data Types

(updated at )

Python Variables

(updated at )

Python Comments

(updated at )

Python Syntax

(updated at )

Python Getting Started

(updated at )

Python Introduction

(created at )

What is Python?

(updated at )

Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering

(updated at )

Machine Learning Types and Programming Languages

(updated at )

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship

(updated at )

Mastering Excel Data Manipulation with Python

(updated at )

Challenge: One Code Problem Per Day

(created at )

Clean Python Environments: The Power of venv vs. Docker

(updated at )

OTHER POSTS IN THE SAME CATEGORY

Clean Python Environments: The Power of venv vs. Docker

(updated at )

How to Build Llama 3 AI Apps with Python: Setup & User Prompts

(updated at )

Mastering Excel Data Manipulation with Python

(updated at )

Try...Catch Helps Ignoring Data Type Miss-Match Error in Python

(updated at )

RegExp example in Python to exclude javascript from HTML code

(created at )

Python code to convert from Lunar to Solar

(created at )

Python example to download webpage

(updated at )

Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship

(updated at )

Python Modules

(updated at )

Python Scope

(updated at )

Python Iterators

(updated at )

Python Inheritance

(updated at )

Python Classes/Objects

(updated at )

Python Arrays

(updated at )

Python Lambda

(updated at )

Python Functions

(updated at )

Python While Loops/For Loops

(updated at )

Python Conditions and If statements

(updated at )

Python Dictionaries

(updated at )

Python Sets

(updated at )

Python Tuples

(updated at )

Python Comparison Operators

(updated at )

Python Arithmetic Operators

(created at )

Printing string n times

(created at )

String concatenation by join()

(created at )

UPDATES

Harness vs. OpenClaw: Two Very Different "Agents"

(updated at )

Clean Python Environments: The Power of venv vs. Docker

(updated at )

What is Docker? Why is Docker also useful in a development environment?

(created at )

UIUC 2026-2027 Academic Calendar

(updated at )

How to Build Llama 3 AI Apps with Python: Setup & User Prompts

(updated at )

Open-Source LLMs: The AI Revolution

(updated at )

Resume 2.0: Leveling Up for My First Software Gig

(created at )

Not everyone will understand what this man just did

(created at )

UIUC Dorm Guide: Find Your Perfect Fit !!

(updated at )

Unpacking IU's Shopper

(created at )

Jackie Chan's Police Story: The Action Masterpiece

(updated at )

The IVE Story: Identity, 'I AM' Charts, and Influence

(updated at )

Tech Visionaries who graduated at UIUC - You are the Next Turn

(updated at )

Open Databases for Sex Crime Occurrences in the U.S.

(updated at )

Automatically copy text to the clipboard when dragging the mouse in the Cursor

(updated at )

My First Day at University of Illinois-Urvana Champaign

(updated at )

Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure

(updated at )

Sun, Rocks, and Adventure: A Day at Joshua Tree National Park

(updated at )

Sipping the Stars: My Starbucks Adventure

(updated at )

Exciting explore at Sequoia National Park

(updated at )

My Life Shot at Death Valley

(updated at )

Ip Man fights with Muay Thai Master

(created at )

Mad Clown - Don't Die

(created at )

How to get Student Enrollment and Degree Verification at UIUC

(updated at )

LAX Thanksgiving Rush: A Joyful Reunion

(updated at )

ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)

(updated at )

FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'

(updated at )

10CM - To Reach You (너에게 닿기를)

(updated at )

Feeling weak? Transform yourself at the UIUC ARC!

(updated at )

BOYNEXTDOOR - If I Say I Love You

(updated at )

The Future of Software Engineer - AI Engineering

(updated at )

G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025

(updated at )

Lie - Legend song by BIGBANG

(updated at )

Why ROLLBACK is useful when you work with Google Gemini CLI?

(created at )

Reimbursement after Vaccination at McKinley Health Center

(created at )

Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!

(created at )

Common Questions from UIUC school life in terms of CS Program

(created at )

UIUC Immunization Compliance

(created at )

LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...

(created at )

LEE CHANHYUK - Endangered Love (멸종위기사랑)

(created at )

Cupid (OT4/Twin Ver.) - LIVE IN STUDIO | FIFTY FIFTY (피프티피프티)

(created at )

Common methods to improve coding skills

(created at )

US National Holiday in 2026

(created at )

BABYMONSTER “WE GO UP” Band LIVE [it's Live] K-POP live music show

(created at )

BLACKPINK - ‘Shut Down’ Live at Coachella 2023

(created at )

JENNIE - like JENNIE - One of Hot K-POP in 2025

(created at )

BABYMONSTER(베이비몬스터) - DRIP + HOT SOURCE + SHEESH

(created at )

Common Naming Format in Software Development

(created at )

In a life where I don't want to spill even a single sip of champagne - LEE CHANHYUK - Panorama(파노라마)

(created at )

Countries with more males and females - what about UIUC?

(created at )