다형성(Polymorphism)
객체지향 (다형성: Polymorphism)
- 다형성 : 같은 형태의 코드가 각각 다른 동작을 하는 것
- 코드의 양을 줄이고 여러 객체 타입을 하나의 타입으로 관리할 수 있음
class Enemy:
def __init__(self, name):
self.name = name
def move(self):
print(self.name + " passes the mountain")
class Human(Enemy):
def move(self):
print(self.name + " climbs the mountain")
class Fairy(Enemy):
def move(self):
print(self.name + " flies over the mountain")
class Mermaid(Enemy):
def move(self):
print(self.name + " swims through the sea")
부모 클래스인 Enemy 클래스의 move는 name passes the mountain을 출력하지만, Human 클래스의 move는 name climbs the mountain을 출력, Fairy 클래스의 move는 name flies over the mountain을 출력, Mermaid의 move는 name swims the sea를 출력함
enemy1 = Human('Ashenone')
enemy2 = Human('Tarnished')
enemy3 = Fairy('Tina')
enemy4 = Fairy('Binka')
enemy5 = Fairy('Daiyosei')
enemy6 = Mermaid('Wakasaki')
Human 클래스의 오브젝트인 Ashenone, Tarnished의 move는 name climbs the mountain을, Fairy 클래스의 오브젝트인 Tina, Binka, Daiyosei의 move는 name flies over the mountain을, Mermaid 클래스의 오브젝트인 Wakasaki는 name swims through the sea를 출력함