[나도코딩 파이썬 기본편] #9 클래스 Class 따라하기

2022. 2. 2. 03:56독학으로 취업 문 뿌수기/Python

728x90
반응형
SMALL

1, 2. 클래스와 init

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

marine = Unit("마린"405)
tank = Unit("탱크"15035)
  • __init__ : 객체의 생성자 / self를 제외하고 객체(marine, tank)의 유닛(name, hp, damage)과 동일하게 만들어야 한다

3. 멤버변수

wraith1 = Unit("레이스", 80, 5)
print("유닛 이름: {}, 공격력: {}" .format(wraith1.namewraith1.damage))

wraith2 = Unit("빼앗은 레이스"805)
wraith2.clocking = True
if wraith2.clocking == True:
    print("{}는 현재 클로킹 상태입니다." .format(wraith2.name))
  • self.멤버변수: 멤버변수를 클래스 외부에서 쓸 수 있다.  ('.멤버변수'로 불러올 수 있다) (__init__ 함수에서 불러옴)

4. 메소드

class AttackUnit:
    def __init__(selfnamehpdamage):
        self.name = name
        self.hp = hp
        self.damage = damage

    def attack(selflocation):
        print("{} : {} 방향으로 적군을 공격합니다. [공격력 {}]" .format(self.namelocationself.damage))

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

firebet1 = AttackUnit("파이어뱃"5016)
firebet1.attack("5시")
firebet1.damaged(25)
firebet1.damaged(25)
  
  • 'self.' 이 붙지 않은 변수는 init가 아닌 변수가 소속되어 있는 함수(attack, damaged)에서 바로 받아온다.
  • init 함수를 먼저 설정하면 다른 함수에서는 self를 제외한 변수만 값을 설정하면 된다.

5. 상속

#일반유닛
class Unit:
    def __init__(selfnamehp):
        self.name = name
        self.hp = hp

#공격유닛
class
 AttackUnit(Unit):
    def __init__(selfnamehpdamage):
        Unit.__init__(self, name, hp)
        self.damage = damage
  • 공격유닛은 일반유닛(겹치는 부분)을 상속받아 생성. >>> Unit.__init__(self, name, hp)
  • 공격력은 추가로 정의해 준다. >>> self.damage = damage

6. 다중 상속

class Flyable:
    def __init__(selfflying_speed):
        self.flying_speed = flying_speed
   
    def fly(selfnamelocation):
        print("{} : {} 방향으로 날아갑니다. [속도 {}]" .format(namelocationself.flying_speed))
 
class FlyableAttackUnit(AttackUnitFlyable):
    def __init__(selfnamehpdamageflying_speed):
        AttackUnit.__init__(selfnamehpdamage)
        Flyable.__init__(selfflying_speed)

valkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시")
 

7. 메소드 오버라이딩

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

    def move(selflocation):
        print("[지상 유닛 이동]")
        print("{} : {} 방향으로 이동합니다. [속도 {}]" .format(self.namelocationself.speed))
 
 
class AttackUnit(Unit):
    def __init__(selfnamehpspeeddamage):
        Unit.__init__(selfnamehpspeed)
        self.damage = damage
 
 
class Flyable:
    def __init__(selfflying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{} : {} 방향으로 날아갑니다. [속도 {}]" .format(name, location, self.flying_speed))
 
 
class FlyableAttackUnit(AttackUnitFlyable):
    def __init__(selfnamehpdamageflying_speed):
        AttackUnit.__init__(selfnamehp0damage# 지상 speed 0
        Flyable.__init__(selfflying_speed)

    def move(selflocation):
        print("[공중 유닛 이동]")
        self.fly(self.namelocation)

vulture = AttackUnit("벌쳐", 80, 10, 20)
battlecruiser = FlyableAttackUnit("배틀크루저", 500, 25, 3)

vulture.move("11시")
battlecruiser.move("9시")
  • vulture은 지상 유닛이고 battlecruiser은 공중 유닛으로 다른 유닛이지만 둘다 move 함수를 쓰기 위해 FlyableAttackUnit 내 move 함수를 새로 만들어 self.fly(self.name,location)으로 Flyable 내 fly 함수와 연동시켰다.
  • 따라서 둘다 같은 move 함수를 쓰지만 벌쳐는 지상유닛으로 배틀크루저는 공중유닛으로 다르게 출력된다.

8. Pass

class BuildingUnit(Unit):
    def __init__(selfnamehpspeed):
        pass
 
  • pass란 출력하지 않고 넘어감을 의미

9. Super

class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        1) Unit.__init__(self, name, hp, 0) # 지상 speed 0
        2) super().__init__(name, hp, 0)
        self.location = location
 
  • (1)과 (2)는 표현 형식만 다를 뿐 같은 값을 출력한다. 
  • super를 이용할 때는 ( )를 뒤에 써주어야 하며 self는 넣지 않는다.
  • 다중상속을 할 때는 사용하지 말 것. super 함수는 맨 처음 유닛에만 적용된다.

Quiz. 아래 정보를 출력하기 위한 코드 작성하기
'총 3대의 매물 / 강남 아파트 매매 10억 2010년 / 마포 오피스텔 전세 5억 2007년 / 송파 빌라 월세 500/50 2000년'

class House:
    def __init__(selflocationhouse_typedeal_typepricecompletion_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.locationself.house_typeself.deal_typeself.priceself.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("총 {}대의 매물이 있습니다." .format(len(houses)))
for house in houses:
    house.show_detail()
  • 위치, 집 유형, 거래 유형, 가격, 준공 년도를 각각 변수로 표현한다.
  • 최종 출력하고자 하는 값을 함수로 정리한다. (show_detail)
  • 변수를 리스트 형태로 정리한다.
  • houses 리스트 안에 house 1,2,3의 값을 추가한다. (.append)
  • 리스트 안에 포함된 변수의 갯수를 이용하여 총 매물의 수를 출력한다. (len)

강의 메모, 복습용으로 작성된 글입니다.

728x90
반응형
LIST