### 클래스 / init / 맴버변수
# 클래스 : 함수와 변수의 집합, 붕어빵 빵틀과 같음
class Unit:
def __init__(self, name, hp, damage): # init 함수, 생성자
# (marine, tank와 같은 객체를 클래스의 인스턴스로 받음)
self.name = name # 맴버 변수(name, hp, damage)
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)
wraith1 = Unit('레이스', 80, 5)
# 클래스 외부에서 맴버변수를 사용하는법 객체명.클래스맴버변수명
print('유닛 이름: {0}, 공격력 : {1}'.format(wraith1.name, wraith1.damage))
wraith2 = Unit('빼앗은 레이스', 80, 5)
wraith2.clocking = True # 클래스 외부에서 원하는 변수를 확장
if wraith2.clocking == True: # 확장된 변수는 확장 객체에만 사용가능
print('{0}는 현재 클로킹 상태입니다.'.format(wraith2.name))
### 일반유닛
class Unit: # 부모 클래스
def __init__(self,name,hp):
self.name = name
self.hp = hp
### 공격유닛 (일반유닛 클래스를 상속함)
class AttackUnit(Unit): # 자식 클래스
def __init__(self, name, hp, damage): #__init__ (생성자)
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, 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('4시')
firebat1.damaged(25)
firebat1.damaged(25)
### 다중 상속
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, damage)
Flyable.__init__(self, flying_speed)
dropship = Flyable
valkyrie = FlyableAttackUnit('발키리', 200, 6, 5)
valkyrie.fly(valkyrie.name, '3시')
valkyrie.attack('4시')
valkyrie.damaged(50)
### 메소드 오버라이딩
# 부모 클래스의 메소드 말고 자식 클래스의 메소드를 정의해서
# 새롭게 쓰고 싶을때 오버라이딩
### 일반유닛 (Speed 추가)
class Unit:
def __init__(self,name,hp, speed):
self.name = name
self.hp = hp
self.speed = speed
def move(self, location): # move 매소드(함수) 추가
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, hp, speed)
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, 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):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 스피드는 0
# super().__init__(self, name, hp, 0, damage) # Super 기능으로도 작성가능
Flyable.__init__(self, flying_speed)
def move(self, location): # 메서드 오버라이딩을 위해 move 매서드 생성
print('[공중 유닛 이동]')
self.fly(self.name, location)
vulture = AttackUnit('벌처', 80,10,20)
Battlecrusier = FlyableAttackUnit('배틀크루져',500,25,3)
vulture.move('11시')
Battlecrusier.fly(Battlecrusier.name, '9시')
# 지상은 move, 공중은 fly를 써야 움직이는데 이걸 하나의 매서드로 통일하고싶다.
# 이때 매서드 오버라이딩을 수행
# 공중 유닛도 move로 움직이게 끔 수정
# FlyableAttackUnit 클래스에 move 매서드 추가
Battlecrusier.move('9시')
### Pass
# 건물 (pass 예시)
class BuildingUnit(Unit):
def __init__(self, name, hp, location):
pass # 함수의 오류가 있더라도 일단 pass
supply_depot = BuildingUnit('서플라이 디폿',500,'7시')
# 신규 (pass 예시)
def game_start():
print('[알림] 새로운 게임을 시작합니다.')
def game_over():
pass
game_start()
game_over()
### Super
class Unit:
def __init__(self):
print('유닛 생성자')
class Flyable:
def __init__(self):
print('플라이어블 생성자')
class FlyableUnit(Unit, Flyable):
def __init__(self):
super().__init__() # Unit 을 받음
dropship = FlyableUnit() # '유닛 생성자 출력
### 문제 8
'''주어진 코드를 활용하여 부동산 프로그램을 작성하시오.
(출력예제)
총 3 가구의 매물이 있다.
강남 아파트 매매 10억 2010년
마포 오피스텔 전세 5억 2007년
송파 빌라 월세 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
print('{0} 매물이 등록되었습니다.'.format(self.location))
pass
# 매물 정보 표시
def show_detail(self):
print('{0} {1} {2} {3} {4}'.format(self.location, self.house_type, self.deal_type,\
self.price, self.completion_year))
pass
Gangnam = House('강남','아파트','매매','10억','2010년')
Mapo = House('마포','오피스텔','전세','5억','2007년')
Songpa = House('송파','빌라','월세','500/50','2000년')
Gangnam.show_detail()
Mapo.show_detail()
Songpa.show_detail()
# Answer
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()
* 출처 나도코딩 [파이썬 코딩 무료 강의 (기본편)]
파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩] (youtube.com)
'[Tools] > Python 뿌시기' 카테고리의 다른 글
[Python 문법 7] - 예외처리, 에러 발생시키기, 사용자 정의 예외, finally (1) | 2024.09.26 |
---|---|
[Python 문법 6] - 클래스를 이용한 스타크래프트 만들기 (3) | 2024.09.26 |
[Python 문법 5] - 표준입출력, 출력포맷, 파일 입출력, pickle, with (7) | 2024.09.26 |
[Python 문법 4] - 함수, 전달 값과 반환 값, 기본 값, 키워드 값, 가변인자, 지역변수와 전역변수 (3) | 2024.09.26 |
[Python 문법 3] - if, for, while, continue & break, 한줄 for (6) | 2024.09.26 |