オブジェクト指向でなぜつくるのかを読んでいて、ポリモーフィズム箇所のコードがわからなかったのでPythonで書いてみました。
基本的にJavaでかかれているので理解しづらいということと、コードが全て書かれていたなかたのでちゃんと理解できていなかったです。
コード
ポリモーフィズム箇所
from abc import ABCMeta, abstractmethod
# 元となるAnimalクラス
class Animal(metaclass = ABCMeta):
@abstractmethod
def cry(self):
pass
# 受け継ぎ先のクラス
class Baby(Animal):
def cry(self):
return "オギャー"
class Dog(Animal):
def cry(self):
return "ワン"
class Crow(Animal):
def cry(self):
return "カー"
この様々な動物がなくコードに対して、
相手が誰であっても「泣け/鳴け」指示できるトレーナー(Trainer)クラスを作ります。
ここの箇所が読んだときに理解できていなかったです。
トレーナークラス
class Trainer:
def exucute(self, animal):
print(animal.cry())
このトレーナークラスをどう使うかというと下記の様に使います。
トレーナークラスの使い方
# 各クラスをインスタンス化
trainer = Trainer()
baby = Baby()
dog = Dog()
crow = Crow()
# 引数にインスタンス化した変数を入れる
trainer.exucute(baby)
trainer.exucute(dog)
trainer.exucute(crow)
すると出力結果は下記になります。
出力結果
オギャー
ワン
カー
インスタンス化した変数を代入するという今まで書いたことない書き方の発見につながりました。
せっかく試したのでメモ程度に残しておきます。