Python Polymorphism Tutorial – Complete Guide

Meet Python Polymorphism – a principle that might sound a bit intimidating, but is actually one of the core concepts in Python that makes it such a powerful and efficient language. This tutorial will make it simple and accessible for you, whether you’re a beginner just starting out or an experienced coder looking to deepen your Python knowledge.

Understanding Python Polymorphism

‘Polymorphism’ originates from Greek, where ‘Poly’ means ‘many’ and ‘Morph’ means ‘form’. In the realm of computer science, this principle allows us to have one function or method that can handle different types of objects, leading to code that is more flexible and easier to maintain.

Every programmer, no matter where they are in their career, will find significant value in understanding and using polymorphism. It streamlines your code, increasing efficiency, and optimizes the way that various objects and methods interact, resulting in a smoother and more dynamic execution.

Learning about polymorphism opens the door to implementing more complex, flexible programming structures. It is an essential tool for anyone aiming to make clean, efficient, and scalable code. Plus, understanding polymorphism is a great way to demonstrate to potential employers that you have a solid grasp of key Python principles.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Examples of Polymorphism

Let’s start with a simple example. We’ll create two classes, Cat and Dog. Each class will have a method sound, that returns the sound the animal makes.

class Cat:
  def sound(self):
    return "Meow"

class Dog:
  def sound(self):
    return "Woof"

With polymorphism, we can define one function that can take either of the classes as a parameter, like this:

def animal_sound(animal):
  return animal.sound()

And here is how we could use the function:

cat = Cat()
dog = Dog()

print(animal_sound(cat))  # Outputs "Meow"
print(animal_sound(dog))  # Outputs "Woof"

More Complex Examples

We can also take this a step further. For example, let’s create a new class, Bird, that also has a sound function:

class Bird:
  def sound(self):
    return "Chirp"

Without changing our animal_sound function, we can pass in an instance of the Bird class:

bird = Bird()

print(animal_sound(bird))  # Outputs "Chirp"

Polymorphism isn’t limited to classes. Functions that take in different data types as parameters can also be considered polymorphic. A function that can take either a string or an integer as a parameter is an example:

def add(a, b):
  return a + b

print(add(5, 7))    # Outputs "12"
print(add("Hi, ", "Zenva"))  # Outputs "Hi, Zenva"

This is the power of Python Polymorphism – the flexibility to handle different types of objects and data seamlessly!

Applying Polymorphism with Inheritance

Polymorphism becomes particularly effective when combined with inheritance. Let’s expand our initial example to illustrate this. We’ll add a BASE class, Animal, that the Dog, Cat, and Bird classes will inherit from:

class Animal:
  def sound(self):
    return "Generic animal sound"

class Cat(Animal):
  def sound(self):
    return "Meow"

class Dog(Animal):
  def sound(self):
    return "Woof"

class Bird(Animal):
  def sound(self):
    return "Chirp"

Now, each animal is an instance of Animal, but they each have their own unique implementation of the sound method.

Using Abstract Base Classes

Python supports a form of polymorphism known as Abstract Base Classes (ABCs). These are classes that contain one or more abstract methods – methods declared but not implemented. Subclasses of the ABC are required to provide implementations for these methods.

from abc import ABC, abstractmethod

class AbstractAnimal(ABC):
  @abstractmethod
  def sound(self):
    pass

class Cat(AbstractAnimal):
  def sound(self):
    return "Meow"

class Dog(AbstractAnimal):
  def sound(self):
    return "Woof"

Polymorphism with Built-In Functions

There are various built-in functions in Python that use polymorphism. Let’s apply the len() function to different data types:

print(len("Hello, Zenva!"))  # Outputs 12
print(len([1, 2, 3, 4, 5]))  # Outputs 5

A concrete illustration of polymorphism at work.

Polymorphism in Real-Life Coding

Understanding the theory behind polymorphism is just one step – let’s see it in action in a real-life coding situation.

class Email:
  def send(self, message):
    return f'Sending "{message}" via Email.'

class SMS:
  def send(self, message):
    return f'Sending "{message}" via SMS.'

def send_message(messenger, message):
  return messenger.send(message)

email = Email()
sms = SMS()

print(send_message(email, "Hello, Zenva!"))  # Outputs 'Sending "Hello, Zenva!" via Email.'
print(send_message(sms, "Hello, Zenva!"))  # Outputs 'Sending "Hello, Zenva!" via SMS.'

In the example above, regardless of the type of object, the send_message function can handle it, thanks to polymorphism.

Where to go next?

Now that you have a solid grasp on the subject of polymorphism, it’s the perfect time to keep that momentum going! The more you learn and practice, the more these concepts will become second nature, enhancing your coding capabilities and opening up new possibilities for you.

We recommend our comprehensive Python Mini-Degree. It’s a vibrant collection of courses on Python programming covering everything from coding basics and algorithms to object-oriented programming, game development, and app development with renowned libraries like Pygame, Tkinter, and Kivy.

Crafted with both beginners and seasoned programmers in mind, these courses feature step-by-step projects designed to help you build, apply, and reinforce your Python skills.

The Mini-Degree offers flexibility; the courses are available 24/7 for you to progress at your own pace. You’ll have the chance to consolidate your learning through quizzes and exciting coding challenges.

Plus, you will build up an impressive portfolio of Python projects that will serve as compelling evidence of your expertise when dealing with potential employers. The courses are instructed by certified professionals, assuring quality and meaningful insights.

If you’re already comfortable with the basics and ready for more challenging material, we’ve got you covered. Explore our catalog of Intermediate Python Courses.

Conclusion

Mastering concepts like Polymorphism is an integral part of your Python journey. This understanding allows you to write code that is more flexible, cleaner and better positioned for growth and change. As you continue to sharpen your Python skills, you’ll find that these fundamental principles will shape your coding style and approach, gradually making you a more refined and resourceful coder.

At Zenva, we’re here to constantly equip you with the skills that will allow you to level up. Whether you’re exploring our comprehensive Python Mini-Degree or diving into our array of Intermediate Python Courses, we’ve got you covered. Let’s continue to explore the dynamic landscape of Python together!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.