본문으로 바로가기

메소드 오버라이딩

category onYouTube/Python 2021. 3. 14. 17:32
  • 오버라이딩 : 상속 관계에 있는 클래스 간에 같은 이름의 메소드를 정의하는 기술

class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))

class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, speed, hp)
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 이동합니다. [속도 {2}]".format(self.name, location, self.speed))

class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]".format(name, location, self.flying_speed))

class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed : 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

vulture = AttackUnit("벌쳐", 80, 10, 20)
battlecruiser = FlyableAttackUnit("배틀크루저", 200, 6, 5)

# 메소드 오버라이딩 덕분에, 각 인스턴스가 지상 유닛인지 공중 유닛인지 구분하지 않고 move()로 사용 가능
vulture.move("11시")
battlecruiser.move("9시") # 메소드 오버라이딩이 아니었다면 fly()를 사용해야 함

 

 

-출처-

www.youtube.com/watch?v=kWiCuklohdY&t=10728s

'onYouTube > Python' 카테고리의 다른 글

에러 발생시키기  (0) 2021.03.14
예외 처리  (0) 2021.03.14
다중 상속  (0) 2021.03.14
상속  (0) 2021.03.14
클래스 메소드  (0) 2021.03.14