ポリモーフィズム
高度なOOPの概念を学びます。
「ポリモーフィズム」はCoddyKit上の無料Python For Kidsレッスンです。 これはレッスン5/5です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはPython For Kids学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Python For Kidsコースには全5レッスンが含まれています。
ポリモーフィズム
オブジェクト指向プログラミング(OOP)のレッスンに戻ってきました。今日は、オブジェクトが複数の形を取ることを可能にする強力な概念、ポリモーフィズムについて学びます。

ポリモーフィズムとは
ポリモーフィズムはOOPの基本概念で、異なるクラスのオブジェクトを共通のスーパークラスのオブジェクトとして扱えるようにします。同じメソッドでも、それを呼び出すオブジェクトに応じて異なる動作をさせることができます。
- 定義:「多様な形」— 異なるオブジェクトが同じメソッド呼び出しに対して、それぞれ異なる応答をする機能です。
- 目的:オブジェクトを相互に置き換えて使用できるようにし、コードの柔軟性と統合性を高めます。
Pythonでポリモーフィズムがどのように機能するか見てみましょう。
ポリモーフィズムの実装
Pythonでは、メソッドのオーバーライドや、異なるオブジェクト型で動作する組み込み関数を使ってポリモーフィズムを実現できます。
- メソッドのオーバーライド:親クラスですでに定義されているメソッドを、子クラスで再定義することです。
- 組み込み関数:さまざまなデータ型で動作する
len()などの関数です。
メソッドのオーバーライドについて詳しく見てみましょう。
メソッドのオーバーライド
メソッドのオーバーライドを使うと、子クラスで、親クラスにすでに定義されているメソッドの具体的な実装を提供できます。これはポリモーフィズムの重要な要素です。
例:
# Defines the Animal parent class with a speak method
class Animal:
def speak(self):
print("The animal makes a sound.") # Generic speak method
オーバーライドしたメソッドを持つ子クラスの作成
Animalを継承する子クラスを作成し、speakメソッドをオーバーライドして、それぞれ固有の動作を定義してみましょう。
例:
# Defines the Dog child class inheriting from Animal
class Dog(Animal):
def speak(self):
print("The dog barks.") # Overridden speak method
# Defines the Cat child class inheriting from Animal
class Cat(Animal):
def speak(self):
print("The cat meows.") # Overridden speak method
オーバーライドしたメソッドでポリモーフィズムを使用する
次に、子クラスのオブジェクトを作成し、同じメソッド名を使いながら異なる動作をする様子を見てみましょう。
例:
# Creates objects of Dog and Cat classes
dog = Dog()
cat = Cat()
# Calls the speak method on both objects
dog.speak() # Output: The dog barks.
cat.speak() # Output: The cat meows.
組み込み関数でポリモーフィズムを使用する
ポリモーフィズムはユーザー定義クラスに限られません。len()のようなPythonの組み込み関数は異なるデータ型で動作し、ポリモーフィックな動作を示します。
例:
# Uses len() with a list
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4
# Uses len() with a string
my_string = "Hello"
print(len(my_string)) # Output: 5
# Uses len() with a dictionary
my_dict = {"a": 1, "b": 2}
print(len(my_dict)) # Output: 2
プログラム例:図形の面積計算
ポリモーフィズムを使って、さまざまな図形の面積を計算するプログラムを作成してみましょう。親クラスShapeと、areaメソッドをオーバーライドする子クラスCircleおよびRectangleを定義します。
コード:
# Defines the Shape parent class with an area method
class Shape:
def area(self):
pass # Placeholder method
# Defines the Circle child class inheriting from Shape
class Circle(Shape):
def __init__(self, radius):
self.radius = radius # Sets the radius of the circle
def area(self):
return 3.14 * self.radius ** 2 # Calculates area of the circle
# Defines the Rectangle child class inheriting from Shape
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width # Sets the width of the rectangle
self.height = height # Sets the height of the rectangle
def area(self):
return self.width * self.height # Calculates area of the rectangle
# Creates objects of Circle and Rectangle classes
circle = Circle(5)
rectangle = Rectangle(4, 6)
# Calculates and prints areas using polymorphism
print("Circle Area:", circle.area()) # Output: Circle Area: 78.5
print("Rectangle Area:", rectangle.area()) # Output: Rectangle Area: 24
# Defines the Vehicle parent class with a move method
class Vehicle:
def move(self):
print("The vehicle moves.")
# Defines the Bicycle child class inheriting from Vehicle
class Bicycle(Vehicle):
def move(self):
print("The bicycle pedals forward.")
# Defines the Airplane child class inheriting from Vehicle
class Airplane(Vehicle):
def move(self):
print("The airplane flies in the sky.")
# Creates objects of Bicycle and Airplane classes
bike = Bicycle()
plane = Airplane()
# Calls the move method on both objects
bike.move()
plane.move()
よくできました!
Pythonのポリモーフィズムと、異なるクラスのオブジェクトが同じメソッド呼び出しに対して、それぞれ異なる応答をする仕組みを学びました。ポリモーフィズムによってコードの柔軟性と拡張性が高まり、管理や拡張が容易になります。さらにクラスやメソッドを作成し、ポリモーフィックな動作を活用して理解を深めていきましょう。

よくある質問
「ポリモーフィズム」レッスンは無料ですか?
はい。「ポリモーフィズム」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Python For Kidsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Python For Kidsコースには全5レッスンが含まれています。
「ポリモーフィズム」で何を学びますか?
高度なOOPの概念を学びます。 ブラウザで直接実行するハンズオンコードでPython For Kidsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Python For Kidsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのPython For Kidsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン5/5です。
「ポリモーフィズム」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このPython For Kidsレッスンでコードを書いて実行できますか?
はい。すべてのPython For Kidsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- OOP入門
- クラスとオブジェクトを作成する
- 継承
- カプセル化
- ポリモーフィズム