파이썬 기본 정리(4) - 클래스

yerim·2023년 1월 19일
0

파이썬 기본 정리

목록 보기
4/11

나도코딩 '파이썬 코딩 무료 강의(기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요' 정리

클래스

##클래스
## 마린 : 공격 유닛, 군인. 총을 쏠 수 있음
# name = "마린"   #유닛의 이름
# hp = 40         #유닛의 체력
# damage = 5      #유닛의 공격력
# print("{} 유닛이 생성되었습니다." .format(name))
# print("체력 {0} 공격력 {1}\n" .format(hp, damage))

## 탱크 : 공격 유닛, 탱크. 포를 쏠 수 있는데, 일반 모드 / 시즈 모드.
# tank_name = "탱크"   #유닛의 이름
# tank_hp = 150         #유닛의 체력
# tank_damage = 35      #유닛의 공격력
# print("{} 유닛이 생성되었습니다." .format(tank_name))
# print("체력 {0} 공격력 {1}\n" .format(tank_hp, tank_damage))

## 탱크2 : 공격 유닛, 탱크. 포를 쏠 수 있는데, 일반 모드 / 시즈 모드.
# tank2_name = "탱크"   #유닛의 이름
# tank2_hp = 150         #유닛의 체력
# tank2_damage = 35      #유닛의 공격력
# print("{} 유닛이 생성되었습니다." .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)
# attack(tank2_name, "1시", tank2_damage)

# 클래스를 사용해서 위의 내용을 나타낸다.

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}\n" .format(self.hp, self.damage))
        
        
        
marine1 = Unit("마린", 40, 5)
marine2 = Unit("마린", 40, 5)
tank = Unit("탱크", 150, 35)


## __init__: 생성자
##멤버변수: 클래스 안에 정의된 변수. self.name, self.hp, self.damage 를 멤버변수라 함

# 레이스 : 공중 유닛, 비행기. 클로킹(상대방에게 보이지 않음)
wraith1 = Unit("레이스", 80, 5)
#클래스 외부에서 멤버변수 사용 가능
print("유닛 이름: {0}, 공격력 : {1}" .format(wraith1.name, wraith1.damage))


# 마인드 컨트롤 : 상대방 유닛을 내 것으로 만드는 것(빼앗음)
wraith2 = Unit("빼앗은 레이스", 80, 5)
#clocking이라는 변수는 class내에 없음
#외부에서 객체에 변수를 추가로 할당해서 확장할 수 있다.
#해당 객체만 확장되고, 다른 객체에는 적용되지 않는다.
wraith2.clocking = True

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


메소드

##메소드     
#공격 유닛
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시")

#공격을 2번 받는다고 가정
firebat1.damaged(25)
firebat1.damaged(25)


상속

##상속
#위의 클래스 사용
#일반 유닛
class Unit:
    def __init__(self, name, hp):
        self.name = name
        self.hp = hp


#공격 유닛
#일반 유닛을 상속받아서 공격 유닛의 클래스를 만든다
class AttackUnit(Unit):
    def __init__(self, name, hp, damage):
        #일반유닛의 생성자를 호출하여 name, hp 정의한다.
        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))
                    
                    
#파이어뱃 : 공격 유닛, 화염방사기.
firebat1 = AttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")	# 파이어뱃 : 5시 방향으로 적군을 공격 합니다. [공격력 16]

#공격을 2번 받는다고 가정
firebat1.damaged(25)	# 파이어뱃 : 16 데미지를 입었습니다.
						# 파이어뱃 : 현재 체력은 25 입니다.
firebat1.damaged(25)	# 파이어뱃 : 16 데미지를 입었습니다.
						# 파이어뱃 : 현재 체력은 0 입니다.
						# 파이어뱃 : 파괴되었습니다.
                        
#-------------------------------------------------------------------------------------

##다중상속(여러 부모에게서 상속을 받는 것)
#날 수 있는 기능을 가진 클래스
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))

#드랍쉽: 공중 유닛, 수송기. 마린 / 파이어뱃 / 탱크 등을 수송. 공격 X

#공중 공격 유닛 클래스
#날 수 있는 기능 클래스 와 공격유닛 클래스를 상속받는다.
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, damage)
        Flyable.__init__(self, flying_speed)
        
        
#발키리 : 공중 공격 유닛, 한번에 14발 미사이 발사
valkyrie = FlyableAttackUnit("발키리", 200, 6, 5)
valkyrie.fly(valkyrie.name, "3시")  # 발키리 : 3시 방향으로 날아갑니다. [속도 5]


메소드 오버라이딩

##메소드 오버라이딩
# 자식 클래스에서 정의한 메소드를 쓰고 싶을 때, 메소드를 새롭게 정의하는 것
#(상속 에서 만든 클래스들 수정)
# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):	#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))
        
# 공격 유닛
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, 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):
        AttackUnit.__init__(self, name, hp, 0, damage)  #지상스피드(speed)=0으로 처리
        Flyable.__init__(self, flying_speed)
        
    ##메소드 오버라이딩 
    # move 함수로 지상유닛, 공중유닛을 이동시킬 수 있도록 한다
    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)
    ##메소드 오버라이딩
    
    
#벌쳐 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐", 80, 10, 20)

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


vulture.move("11시")
# battlecruiser.fly(battlecruiser.name, "9시")
battlecruiser.move("9시")	#메소드 오버라이딩으로 move 함수로 공중유닛을 이동시킬 수 있다.


pass & super

##pass : 아무것도 하지 않고 넘어가는 것
class BuildingUnit2():
	pass
    
##super : 부모클래스의 생성자를 호출하는 방법
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        # Unit.__init__(self, name, hp, 0) 대신 super를 사용하여 부모클래스의 생성자 호출
        #super 사용시에는 self X
        super().__init__(name, hp, 0)
        self.location = location
    
#서플라이 디폿 : 건물, 1개 건물 = 8개의 유닛.
supply_depot = BuildingUnit("서플라이 디폿", 500, "7시")


##super 사용 시 다중상속할 때에 문제 발생
#super() 사용 시 -> 상속받는 클래스들 중 맨 처음 클래스에 대해서만 __init__ 함수가 호출됨
#따라서 모든 클래스를 따로따로 초기화해주어야 함
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)
        

#드랍쉽
#super 사용했을 때
# dropship = FlyableUnit()  # Unit 생성자
#따로 초기화해줬을 때
dropship = FlyableUnit()    # Unit 생성자
                            # Flyable 생성자


Quiz 8

##Quiz 8##
#주어진 코드를 활용하여 부동산 프로그램을 작성하시오.
# (출력 예제)
# 총 3대의 매물이 있습니다.
# 강남 아파트 매매 10억 2010년
# 마포 오피스텔 전세 5억 2007년
# 송파 빌라 월세 500/50 2000년

# [코드]
# class House:
#     #매물 초기화
#     def __init__(self, location, house_type, deal_type, price, completion_year):
#         pass
    
#     #매물 정보 표시
#     def show_detail(self):
#         pass



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()
profile
hello!

0개의 댓글