Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Introduction to Polymorphism | Polymorfism
Objektorienterad Programmering i Python

Introduction to Polymorphism

Svep för att visa menyn

Note
Definition

Polymorphism is a core principle of object-oriented programming that lets objects of different types be treated as the same type through a common interface. It makes code more flexible and easier to maintain and extend.

Think of polymorphism as having different objects that all respond to the same method call, but each in its own unique way. For example, calling a speak() method on different animals gives different results:

  • A Dog returns "Woof!";
  • A Cat returns "Meow!";
  • A Cow returns "Moo!".

The method name stays the same, but each object provides its own implementation.

Note
Note

Without polymorphism, code requires separate functions and complex conditionals, making it harder to extend and prone to duplication and maintenance issues.

Python supports several forms of polymorphism, each providing a different way for objects to share a common interface while behaving uniquely.

Duck typing
expand arrow

Allows you to use objects based on their behavior (methods/attributes they have) instead of their type.

Method overriding
expand arrow

Allows a subclass to provide its own implementation of a method inherited from a parent class, enabling specialized behavior.

Operator overloading
expand arrow

Redefines how operators (+, -, *, etc.) behave for custom objects, making them work in a natural, intuitive way.

Abstract base classes (ABCs)
expand arrow

Defines formal contracts that subclasses must follow, ensuring consistency and structured design across implementations.

Consider a real-world media player example. The MediaPlayer class doesn’t need to know whether it’s handling an AudioFile, VideoFile, or ImageFile. It simply calls the play() method on each media object, and each type handles playback in its own appropriate way. This is exactly what polymorphism allows us to do.

question mark

What is the main purpose of polymorphism in OOP?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 4. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 4. Kapitel 1
some-alt