클래스.py

2023. 3. 17. 15:50·python

 

## 클래스
# 공격 함수
def attack(name, location, damage):
    print("{}:{} 방향으로 적군을 공격합니다. [공격력{}]"\\
          .format(name, location, damage))

# class : 붕어빵 기계로 많이 묘사된다.
class unit:
    # __init__ : python 에서 쓰이는 생성자, 객채가 생성될때 자동으로 호출되는 부분
    # __init__ 은 특정 초기상태로 커스터마이즈된 인스턴스 객체로 생각하면 된다.
    # class로부터 만들어지는 요소들을 객체라고 표현함.
    def __init__(self,name, hp, damage) :
        self.name = name
        self.hp = hp
        self.damage = damage
        print("{}유닛이 생성되었습니다.".format(self.name))
        print("체력 {}, 공격력 {}\\n".format(self.hp, self.damage))

# marine1~tank : unit 클래스의 instance
# 객체가 생성될 때에는 기본적으로 self를 제외한 개수와 동일하게 작성.
marine1 = unit("마린", 40, 5)
marine2 = unit("마린", 40, 5)
tank = unit("탱크", 150, 35)
  • class : 붕어빵 기계로 묘사된다.
  • __init__ : python 에서 쓰이는 생성자, 객채가 생성될때 자동으로 호출되는 부분
    ㄴ 특정 초기상태로 커스터마이즈된 인스턴스 객체로 생각하면 된다.
  • 객체 생성은 객체명 = class명(변수1, 변수2, …. ) 으로 한다.
## 멤버변수
# 클래스 내에 정의된 변수로, 변수를 사용할 수 있음.
wraith1 = unit("레이스", 80, 5)
print("유닛 이름 : {0}, 공격력 : {1}".format(wraith1.name, wraith1.damage))

wraith2 = unit("빼앗긴 레이스", 80, 5)
# Unit 클래스에 clocking이라는 변수는 없음
# wraith2 에 clocking이라는 변수를 추가로 할당 후 true를 입력.
wraith2.clocking = True
if wraith2.clocking == True:
    print("{}는 현재 클로킹 상태입니다.".format(wraith2.name))
  • 멤버변수는 클래스 내 정의된 변수.
  • 만약 객체생성 시, class에 없는 변수를 추가하고 싶을 때,
    객체명.변수 = 값 으로 해당 객체의 변수를 추가 및 값을 할당할 수 있다.
## 메소드
class AttackUnit:
    def __init__(self, name, hp, damage):
        self.name = name
        self.hp = hp
        self.damage = damage
    # 메소드 : 객체에 속하는 함수, 즉 attack, damaged 등이다.
    def attack(self, location):
        # self.~ 는 자기자신에게 있는 멤버변수 값을 출력하는것.
        # self 없는 변수는 전달받은 값을 출력하는것.
        print("{} : {} 방향으로 적군을 공격합니다. [공격력 : {}]"\\
              .format(self.name, location, self.damage))
    def damaged(self, damage):
        print("{} : {} 데미지를 입었습니다."\\
              .format(self.name,damage))
        self.hp -=damage
        print("{} : 현재 체력은 {} 입니다.". format(self.name, self.hp))
        if self.hp<=0:
            print("{} : 파괴되었습니다.".format(self.name))

firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")
firebat1.damaged(25)
firebat1.damaged(25)
  • 메소드는 객체에 속해있는 함수를 뜻한다.
  • 객체명.함수(값) 을 통해 메소드를 호출할 수 있다.
## 상속
class unit:
    def __init__(self,name, hp, speed) :
        self.name = name
        self.hp = hp
        self.speed = speed
    def move(self, location):
        print("[지상 유닛 이동]")
        print("{} : {} 방향으로 이동합니다. [속도 {}]"\\
              .format(self.name, location, self.speed))

class AttackUnit(unit):
    def __init__(self, name, hp, damage, speed):
        # self.name ~ speed는 unit 클래스에서도 사용하고 있음.
        # unit 클래스 내용을 상속받아서 attackunit 만들 수 있음.
        '''
        self.name = name
        self.hp = hp
        self.speed = speed
        '''
        # unit 에서 만들어진 생성자를 호출해서 이름/체력 정의 가능.
        unit.__init__(self, name, hp, speed)
        self.damage = damage
    def attack(self, location):
        print("{} : {} 방향으로 적군을 공격합니다. [공격력 : {}]"\\
              .format(self.name, location, self.damage))
    def damaged(self, damage):
        print("{} : {} 데미지를 입었습니다."\\
              .format(self.name,damage))
        self.hp -=damage
        print("{} : 현재 체력은 {} 입니다.". format(self.name, self.hp))
        if self.hp<=0:
            print("{} : 파괴되었습니다.".format(self.name))

firebat1 = AttackUnit("파이어뱃", 50, 16, 10)
firebat1.attack("5시")
firebat1.damaged(25)
firebat1.damaged(25)
  • AttackUnit 을 보면 unit 클래스를 상속받는다.
    ㄴ unit에서 만들어진 변수를 정의 및 함수 사용이 가능하다.
## 다중상속.
# 공중유닛, 수송기, 마린 / 파이어뱃 / 탱크 등을 수송 (공격X)
class flyable:
    def __init__(self, flying_speed) :
        self.flying_speed = flying_speed

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

# 공중 + 공격 유닛  
class Flyable_Attack_unit(AttackUnit, flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, damage, 0) # 지상 스피드는 0
        flyable.__init__(self,flying_speed)
    # self.fly를 호출함으로서 move를 통해서도 fly함수를 호출하도록 함.
    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

valkyrie = Flyable_Attack_unit("발키리",200,6,5)
# Flyable 의 fly 에는 초기화된 name, location 변수가 없어서 따로 지정
# 반면 flying_speed 정보는 포함되어있어 지정 X
valkyrie.fly(valkyrie.name,"3시")
  • 다중 상속은 하나의 클래스에 여러 클래스를 상속받는것을 의미한다.
  • Flyable_Attack_unit을 보면 AttackUnit flyable 을 상속받는다.
## 메소드 오버라이딩
# 자식메소드에서 정의한 메소드를 부모 메소드에서 쓰고싶을 때, 쓰는방법.
vulture = AttackUnit("벌쳐", 80, 10, 20)
battlecruiser = Flyable_Attack_unit("배틀크루저",500, 25, 3 )

# unit 함수의 move를 호출함
vulture.move("11시")
# battlecruiser.fly(battlecruiser.name, "9시")
# 상속받은 AttackUnit>Unit>move 함수를 호출하는 것이 아니고
# Flyable_Attack_unit 에 재정의된 move함수를 호출함.
battlecruiser.move("9시")
  • Flyable_Attack_unit 에는 상속받은 AttackUnit>Unit>move 함수와
    Flyable_Attack_unit 의 move 함수가 있는데, 호출했을 때
    상속받은 메소드를 무시하고 클래스에서 새로만든 메소드를 사용한다.
  • 어떠한 기능이 같은 메소드의 이름으로 계속 사용되어야 할때 사용한다.
## pass
class Building_Uint(unit):
    def __init__(self, name, hp, location):
        # 일단 아무것도 안하고 넘어감.
        pass

# 서플라이 디폿 : 건물, 1개 건물 = 8unit
supply_depot = Building_Uint("서플라이 디폿", 500, "7시") 

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

game_start()
game_over()
  • pass는 아무것도 하지 않고 넘어가겠다는 의미
## super
class BuildingUint(unit):
    def __init__(self, name, hp, location):
        # super 을 사용하면 상속받는 부모클래스(unit) 초기화 가능.
        # unit.__init__(self, name, hp, 0) 와 동일하게 작동한다.
        # 다만 다중상속인 경우, 처음에 있는 class만 호출된다.
        super.__init__(name, hp, 0)
        self.location = location
  • super 을 사용하면 상속받는 부모클래스(unit) 초기화 가능.
    ㄴ unit.init(self, name, hp, 0) 와 동일하게 작동한다고 생각하면 됨.
    ㄴ 다만 다중상속의 경우, 처음에 있는 class에게만 적용됨
## 퀴즈
'''
총 3개의 매물이 있습니다.
1. 강남아파트 매매 10억 2010년
2. 마포 오피스텔 전세 5억 2007년
3. 송파 빌라 월세 500/50 2000년
'''

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("{0} {1} {2} {3} {4}년".format(self.location, self.house_type,\\
                         self.deal_type, self.price, self.completion_year))

# 클래스도... 리스트에 넣을수 있다니..!!
houses = []
house = House("강남", "아파트", "매매", "10억", "2010")
houses.append(house)
house = House("마포", "오피스텔", "전세", "5억", "2007")
houses.append(house)
house = House("송파", "빌라", "월세", "500/50", "2000")
houses.append(house)

print("총 {}개의 매물이 있습니다.".format(len(houses)))
for house in houses:
    house.show_detail()
  • 클래스도 리스트에 포함시킬 수 있다!!

'python' 카테고리의 다른 글

모듈과 패키지.py  (0) 2023.03.20
예외처리.py  (0) 2023.03.17
표준입출력.py  (0) 2023.03.14
함수.py  (0) 2023.03.11
분기.py  (0) 2023.03.11
'python' 카테고리의 다른 글
  • 모듈과 패키지.py
  • 예외처리.py
  • 표준입출력.py
  • 함수.py
몽자비루
몽자비루
코딩공부 정리용 블로그입니다.
  • 몽자비루
    공부하는 블로그
    몽자비루
  • 전체
    오늘
    어제
    • 분류 전체보기 (165) N
      • python (30)
        • python_selenium (16)
        • python_pygame (3)
      • appium (0)
      • 쿠버네티스 (60)
        • linux (8)
        • shell programming (8)
        • docker (18)
        • cka (23)
      • postman&API (16)
      • QA성장하기 (30)
        • 개발자에서 아키텍트로 스터디 (6)
        • 소프트웨어 공학 이해도 높이기 (6)
        • 테스팅 전문 지식 쌓기 (18)
      • 에러일기 (1)
      • AWS (27) N
      • Jmeter (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    네트워크 테스트
    qa
    포스트맨
    API
    QAKOREA
    테스트 결과보고서
    스터디
    테스트 계획서
    개발자에서아키텍트로
    e2c
    로스트아크api
    k8s
    애플리케이션로그
    테스트 계획서 만들어보기
    python
    테스트스크립트
    로스트아크
    postman
    cka
    리눅스
    쿠버네티스
    application log
    vi에디터
    공존성테스트
    .cpu
    도커
    linux
    앱공존성
    LOSTARK
    사드웨어리소스
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
몽자비루
클래스.py
상단으로

티스토리툴바