DEV Community

Cover image for Advanced Python: OOP polymorphism
Tim
Tim

Posted on

5 2

Advanced Python: OOP polymorphism

A great deal in programming is about the so called 'Object Oriented' side of programming.

Python supports OOP as well. This tutorial will show you how to implement polymorphism in your Object Oriented code.

Polymorphism is all about a superclass that has multiple subclasses. The subclasses inherit from the superclass and the superclass doesn't need to know which subclass is currently inheriting and executing.
Don't worry if this doesn't make sense yet, take a look at the following example for clarification:

Let's say we have a program that shows images, but the image can be either of PNG or JPG format. In our case the program will print different things based on the format of the image.

So we'll start by making the base class that all the subclasses will inherit from. The class will also print an error when the image has a wrong extension.

Now onto the subclasses which will inherit from the 'Image' class. The classes also have a method called 'show' which will print a custom message.
Notice how the parent/superclass doesn't need to know which subclass is inheriting in order to work.

Now let's make the objects and call the 'show' methods:

And here's the output:

I hope you learned something and see you in the next post :) !

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

๐Ÿ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someoneโ€™s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay