[TIL] Python class(2탄)

이나현·2021년 6월 24일
0

python

목록 보기
8/10
post-thumbnail

class 관련 공부 2탄

매소드 오버라이딩

class 내에 타 class에 정의되어 있는 함수를 재정의해줌으로써 똑같은 함수명을 쓰면 똑같은 쓰임으로 나타날 수 있게 만듦

1) 벌처: 지상 유닛, 기동성이 좋은 유닛을 만듦
부모 클래스인 unit에 move함수 추가

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))
vulture = AttackUnit("벌쳐", 80, 10, 20)
vulture.move("11시") //[지상 유닛 이동]
                      벌쳐: 11시 방향으로 이동합니다. [속도 10]

2)배틀크루저: 공중유닛, 체력 굿, 공격력이 좋은 유닛을 만듦

FlyableAttackUnit에 move 함수를 추가

class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage)  # 지상 스피드는 0으로 처리
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)
battlecruiser = FlyableAttackUnit("배틀크루저", 500, 30, 3)
battlecruiser.move("9시")// [공중 유닛 이동]
                            배틀크루저: 9시 방향으로 날아갑니다. [속도 3]

결과: 똑같은 함수명인 move를 사용할 수 있음

pass

아무것도 안하고 일단은 넘어감

1) 건물

class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        pass

2) 유닛생성- 서플라이 디폿: 건물, 1개 건물 = 8 유닛
supply_depot = BuildingUnit("서플라이 디폿", 500, "7시")

3) 예시

def game_start():
    print("[알림] 새로운 게임을 시작합니다.")


def game_over():
    pass


game_start()// 결과값이 나옴
game_over()// 결과값이 안 나옴

super

super를 통해 부모 클래스 상속이 가능하다.
단, super는 파라미터의 순서에 따라 출력되는 값이 다르다. 따라서 상속받은 모든 값을 출력하고 싶을 때에는 각각 작성해주는 것이 best이다.

class Unit:
    def __init__(self):
        print("Unit 생성자")


class Flyable:
    def __init__(self):
        print("Flyable 생성자")


class FlyableUnit(Flyable, Unit):
    def __init__(self):
        # super().__init__() // 순서에 따라 하나씩만 출력됨
        Unit.__init__(self)
        Flyable.__init__(self)


dropship = FlyableUnit()
profile
technology blog

0개의 댓글