+91 81900 98289

Python Polymorphism

This Python Polymorphism lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

Polymorphism means different objects can answer the same method name. A loop can call label() without asking which class each object is.

Python does not require a shared parent for this. If the method exists, the call works.

Example 1: Start here

Keep the shared method name and the meaning aligned. Two label methods should both return a label.

class Pdf: # a template for objects def label(self): # define the function; it runs when you call it return "PDF" # send this value back to the caller class Sheet: # a template for objects def label(self): # define the function; it runs when you call it return "Sheet" # send this value back to the caller for item in (Pdf(), Sheet()): # repeat the indented lines once per value print(item.label())

Example 2: Same call, different classes

The loop does not care which class it has, as long as label exists.

class PythonCourse: # a template for objects def label(self): # define the function; it runs when you call it return "Python" # send this value back to the caller class SqlCourse: # a template for objects def label(self): # define the function; it runs when you call it return "SQL" # send this value back to the caller for course in (PythonCourse(), SqlCourse()): # repeat the indented lines once per value print(course.label())

Example 3: A shared parent

The child supplies its own label. Callers can still treat it as a Course.

class Course: # a template for objects def label(self): # define the function; it runs when you call it return "Course" # send this value back to the caller class PythonCourse(Course): # a template for objects def label(self): # define the function; it runs when you call it return "Python" # send this value back to the caller print(PythonCourse().label())

Example 4: Duck typing

Python uses the methods an object has. The classes do not need a shared parent.

class Batch: # a template for objects def size(self): # define the function; it runs when you call it return 24 # send this value back to the caller class Waitlist: # a template for objects def size(self): # define the function; it runs when you call it return 5 # send this value back to the caller def show(group): # define the function; it runs when you call it print(group.size()) show(Batch()) # call the function show(Waitlist()) # call the function
Keep the shared method name and the meaning aligned. Two label methods should both return a label.
Call Now 81900 98289