Python 에서의 다형성 이해
이 단계에서는 Python 다형성의 기본 사항을 살펴보겠습니다. 다형성 (polymorphism) 을 사용하면 자식 클래스에서 부모 클래스에 정의된 것과 동일한 이름의 메서드를 정의할 수 있습니다. 결과적으로 자식 클래스는 해당 속성과 동작을 상속받습니다. 그러나 특정 조정이나 추가가 필요한 경우, 다형성을 통해 부모 클래스 구조를 변경하지 않고 변경할 수 있습니다.
다양한 도시 시스템 모듈과 상호 작용하기 위한 인터페이스를 나타내는 기본 클래스를 생성하는 것으로 시작합니다.
다음으로, 다음 내용을 ~/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.