LoginSignup
1
4

More than 3 years have passed since last update.

【Python】オブジェクト指向プログラミング基礎vol.6~ポリモーフィズム~

Posted at

ポリモーフィズム

同名のメソッドが、インスタンスによって振る舞いを適切に変えること

以下のプログラムを見ると、

Soccerクラス、Baseballクラス、Basketballクラスすべてがget_score()メソッドを持つ。

class Soccer:
    def get_score(self):
        print('kick')    

class Baseball:
    def get_score(self):
        print('swing')

class Basketball:
    def get_score(self):
        print('throw')

def motion(sports):
    sports.get_score()

soccer = Soccer()
baseball = Baseball()
basketball = Basketball()

motion(soccer)
motion(baseball)
motion(basketball)

実行結果

kick
swing
throw

このように異なるクラスに共通の名前のメソッドを定義することで、どのクラスのオブジェクトかを気にせずget_score()メソッドを使用できるようになっている

しかし、ポリモーフィズムを使わないで実装を行う余地が残ってしまっている

ポリモーフィズムを使わないで実装を強制する方法として、抽象クラス・抽象メソッドを利用する方法がある

抽象(基底)くらすとは

継承されることを前提としたクラス、インスタンスを生成できない

抽象メソッドとは

実装をもたない、インターフェースを規定するためのメソッド、抽象クラスに定義できる

抽象メソッドはサブクラスの中のオーバーライドによって実装されなければいけない

Pythonで抽象クラス・抽象メソッドを利用するには、ABC (Abstract Base Class)モジュールを使う

抽象クラスを定義するにはABCクラスを継承し、抽象メソッドを定義するには@abstractmethodデコレータを使用する

from abc import ABC, abstractmethod

class Sports(ABC):
    @abstractmethod
    def get_score(self):
        pass

class Soccer:
    def get_score(self):
        print('kick')    

class Baseball:
    def get_score(self):
        print('swing')

class Basketball:
    def get_score(self):
        print('throw')

soccer = Soccer()
baseball = Baseball()
basketball = Basketball()

soccer.get_score()
baseball.get_score()
basketball.get_score()

実行結果

kick
swing
throw
1
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4