理解 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.