Pythonにおける多態性の理解
このステップでは、Pythonの多態性の基本を探ります。多態性により、サブクラスに親クラスで定義されたものと同じ名前のメソッドを定義できます。その結果、サブクラスはそのプロパティと振る舞いを継承します。ただし、特定の調整や追加が必要な場合、多態性により親クラスの構造を変更することなく変更が可能です。
まず、さまざまな都市システムモジュールとの相互作用のインターフェイスを表す基底クラスを作成します。
次に、~/project/infrastructure.py
に以下の内容を追加します。
## infrastructure.py
class CitySystem:
def power_on(self):
raise NotImplementedError("Subclass must implement this abstract method")
class TransportationSystem(CitySystem):
def power_on(self):
print("Transportation System is now activated.")
class WasteManagementSystem(CitySystem):
def power_on(self):
print("Waste Management System is now activated.")
## This function represents the city initialization sequence
def initiate_city_systems(systems):
for system in systems:
system.power_on()
## Let’s see polymorphism in action
if __name__ == "__main__":
city_systems = [TransportationSystem(), WasteManagementSystem()]
initiate_city_systems(city_systems)
多態性を使ってシステムが正しく初期化されることをテストするには、次のコマンドを実行します。
python3 ~/project/infrastructure.py
次のような出力が表示され、輸送システムと廃棄物管理システムの両方が活性化されていることがわかります。
Transportation System is now activated.
Waste Management System is now activated.