Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Introduction to Polymorphism | Section
/
Object-Oriented Programming in Python

bookIntroduction to Polymorphism

メニューを表示するにはスワイプしてください

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?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  19

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  19
some-alt