본문 바로가기

_Programming/Python

Basic.클래스

현재까지 우리가 배워온대로 함수를 만들고 그에 따라 행동하는 무엇인가를 한 개씩 만들어 본다.

# 마린 : 공격 유닛, 군인. 총을 쏠 수 있음
name = "마린"
hp = 40
damage = 5

print("{0} 유닛이 생성되었습니다.".format(name))
print("체력 {0}, 공격력 {1}\n".format(hp, damage))

# 탱크 : 공격 유닛, 탱크. 포를 쏠 수 있는데, 일반모드 / 시즈 모드.
tank_name = "탱크"
tank_hp = 150
tank_damage = 35

print("{0} 유닛이 생성되었습니다.".format(tank_name))
print("체력 {0}, 공격력 {1}\n".format(tank_hp, tank_damage))

def attack(name, location, damage):
    print("{0} : {1}시 방향으로 적군을 공격합니다. [공격력 {2}]".format(name, location, damage))

attack(name, "1시", damage)
attack(tank_name, "1시", tank_damage)

 

만약, 마린이나 탱크가 한 개씩이 아니라면...?

----> 붕어빵 틀 같이 계속 찍어낼 수 있도록 틀을 만든다. 이게 바로 'Class'의 개념이다.

 

 

클래스 : 붕어빵 틀 같은 존재. 같은 무엇인가를 몇 가지의 변수만 다르게 생성해 낼 수 있는 틀.
객체 : 클래스로부터 만들어지는 마린과 탱크 같은 놈들.
인스턴스 : 마린과 탱크는 이 유닛클래스의 인스턴스이다.

class Unit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{0}유닛이 생성되었습니다.".format(self.name))
        print("체력{0}, 공격력{1}".format(self.hp, self.damage))

marine1 = Unit("마린", 40, 5)
marine2 = Unit("마린", 40, 5)
tank = Unit("탱크", 150, 35)

# _init_ : 생성자. 초기화. : 객체 생성과 동시에 실행되는 값을 명명함.


# 멤버변수 : 클래스내에서 정의된 변수. '.'으로 멤버변수에 접근.
 # 레이스 : 공중 유닛, 비행기. 클로킹(상대방에게 보이지 않음)
wraith1 = Unit("레이스", 80, 5)
print("유닛이름 : {0}, 공격력 : {1}".format(wraith1.name, wraith1.damage))

# 마인드 컨트롤 : 상대방 유닛을 내 것으로 만드는 것(빼앗음)
wraith2 = Unit("빼앗은 레이스", 80, 5)
wraith2.clocking = True 
# clocking이라는 변수는 원래 클래스에 없는데 클래스 외부에서 객체에 추가로 변수를 만들어 쓸 수 있다.

if wraith2.clocking == True:
    print("{0}는 현재 클로킹 상태입니다.".format(wraith2.name))

 

 

메소드 : 동작을 의미한다. 클래스에 의해 생성된 객체들의 동작을 의미.

# 메소드
# self는 클래스 안에 자기 자신.
class AttackUnit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
        
    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력{2}]".format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, self.damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))
        if(self.hp <=0):
            print("{0} : 파과되었습니다.".format(self.name))

# 파이어백 : 공격 유닛, 화염방사기.
firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")
firebat1.damaged(25)
firebat1.damaged(25)

 

 

다중상속 : 여러 부모에게 상속 받는 것.

# 메딕 : 의무병
# 드라쉽 : 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격기능x

# 날 수 있는 기능을 가진 클래스
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(AttackkUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackkUnit.__init__(self, name, hp, damage)
        Flyable.__init__(self, flying_speed)
        
# 발키리 : 공중 공격 유닛, 한 번에 14발 미사일 발사.
varkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
varkyrie.fly(varkyrie.name, "3시")

 

 

메소드 오버라이딩 : 부모 클래스에서 정의한 것이 아닌 자식 클래스에서 정의한 것을 사용하는것.

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

class AttackUnit(Unit):
    def __init__(self, name, hp, damage):
        Unit.__init__(self, name, hp)
        self.damage = damage 
    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력{2}]"\
        .format(self.name, location, self.damage))

    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, self.damage))
        self.hp -= damage
        print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))
        if(self.hp <=0):
            print("{0} : 파과되었습니다.".format(self.name))
            
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):
        AttackkUnitt.__init__(self, name, hp, 0, damage) # 지상 speed : 0
        Flyable.__init__(self, flying_speed)
        
# 벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackkUnitt("벌쳐", 80, 10, 20)

# 배틀크루저 : 공중 유닛, 체력도 굉장히 좋음, 공격력도 좋음.
battlecruiser = FlyableAttackUnitt("배틀크루저", 500, 25, 3)

vulture.move("11시")
battlecruiser.fly(battlecruiser.name, "9시")
battlecruiser.move("9시")        

 

 

Pass :  클래스나 메소드를 완성하지 않고 일단 넘어 갈 수 있게 하는 것.

class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        pass
 # 서플라이 디폿 : 건물, 1개 건물 = 8 유닛.
supply_depot = BuildingUnit("서플라이 디폿", 500, "7시")

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

game_start()
game_over()

 

 

Super : 상속시 초기화 할 때 self 없이 초기화 할 수 있는 것.

class BuildingUnitt(Unit):
    def __init__(self, name, hp, location):
        #Unit.__init__(self, name, hp, 0) 
        super().__init__(name, hp, 0)
        self.location = location

문제는 다중상속시 super()로 초기화 할 떄인데,

아래 코드를 보면 다중상속하고 super()를 사용했을 때는 상속 중 첫 번째 상속에 대해서만 초기화가 된 것을 알 수 있다.

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

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

class FlyableUnit(Unit, Flyable):
    def __init__(self):
        super().__init__()

dropship = FlyableUnit()  # Unit 생성자
class Unit:
    def __init__(self):
        print("Unit 생성자")

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

class FlyableUnit(Flyable, Unit):
    def __init__(self):
        super().__init__()

dropship = FlyableUnit()  # Flyable 생성자

 

따라서, 다중상속에 경우에는 super()대신에 각각의 클래스를 초기화 해주는 방법을 이용한다.

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

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

class FlyableUnit(Unit, Flyable):
    def __init__(self):
        #super().__init__()
        Unit.__init__(self)
        Flyable.__init__(self)

dropship = FlyableUnit() # Unit 생성자 Flyable 생성자

 

 

Quiz ) 주어진 코드를 활용하여 부동산 프로그램을 작성하시오.

(출력예제)

총 3대의 매물이 있습니다.

강남 아파트 매매 10억 2010년

마포 오피스텔 전세 5억 2007년

송파 빌라 월세 500/50 2000년

# sol
class House:
    # 매물 초기화
    def __init__(self, location, house_type, deal_type, price, completion_year):
        self.location = location
        self.house_type = house_type
        self.deal_type = deal_type
        self.price = price
        self.completion_year = completion_year
    # 매물 정보 표시
    def show_detail(self):
        print(self.location, self.house_type, self.deal_type, self.price, self.completion_year)

houses = []
house1 = House("강남","아파트","매매","10억","2010년")
house2 = House("마포", "오피스텔", "전세", "5억", "2007년")
house3 = House("송파","빌라","월세","500/50","2000년")

houses.append(house1)
houses.append(house2)
houses.append(house3)

print('총 {0}대의 매물이 있습니다.'.format(len(houses)))

for house in houses:
    house.show_detail()

 

 

 

 

출처: www.youtube.com/watch?v=kWiCuklohd

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

Basic.모듈과 패키지  (0) 2020.09.15
Basic.예외처리  (0) 2020.09.14
Basic.입출력  (0) 2020.09.10
Basic.함수  (0) 2020.09.09
Basic.제어문  (0) 2020.09.08