Python

[파이썬] 클래스class (__init__,멤버변수, 메소드)

뉴라코 2024. 11. 9. 13:24

-클래스를 사용하지 않고 유닛을 하나씩 만들 때: 정보값을 유닛마다 하나씩 만들어야해서 불편함.

#마린 : 공격 유닛, 군인, 총을 쏠 수 있음.
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))

tank2_name ="탱크"
tank2_hp =150
tank2_damage =35

print("{0} 유닛이 생성되었습니다".format(tank2_name))
print("체력 {0}, 공격력{1}\n".format(tank2_hp,tank2_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)
Terminal>>
마린 유닛이 생성되었습니다
체력 40, 공격력5

탱크 유닛이 생성되었습니다
체력 150, 공격력35

탱크 유닛이 생성되었습니다
체력 150, 공격력35

마린: 1시방향으로 적군을 공격 합니다. [공격력5]
탱크: 1시방향으로 적군을 공격 합니다. [공격력35]
탱크: 1시방향으로 적군을 공격 합니다. [공격력35]

클래스( 붕어빵 틀이라고 생각. 재료만 넣으면 무한대 만들 수 있음)
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)
Terminal>>
마린유닛이 생성되었습니다.
체력40, 공격력5
마린유닛이 생성되었습니다.
체력40, 공격력5
탱크유닛이 생성되었습니다.
체력150, 공격력35

 

1. unit이라는 클래스를 만들고 __init__함수를 정의한다. 

2. sefl.변수 = 변수 라는 것을 통해 하나씩 변수 값을 입력하지 않아도 되도록 한다. 

3. 마린,탱크와 같은 것을 '객체'라고 부른다. 클래스로부터 만들어진 것. unit class의 instance라고 표현.

4. 객체가 생성될 때는 __init__함수에서  self 빼고 동일하게 값을 던져줘야함.

ex. tank=unit("탱크") 라고만 하면 안됨 hp,damage 값 빠졌기 때문에 오류 생김.


멤버변수

:클래스 내에서 정의된 변수(self.name, self.hp, self.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}".format(self.hp, self.damage))
        
#레이스 : 공중 유닛, 비행기, 클로킹(상대방에게 보이지 않음)
wraith1=unit("레이스",80,5)        
print("유닛 이름:{0}, 공격력:{1}".format(wraith1.name, wraith1.damage)) #외부에서 멤버변수 사용
Terminal>>
레이스유닛이 생성되었습니다.
체력80, 공격력5  #이 두 줄은 wraith1=unit에 대한 클래스 안에 있는 함수 사용
유닛 이름:레이스, 공격력:5 # 이 부분이 클래스 외부에서 쓴 print 멤버변수 사용했을 때

1.클래스 외부에서 멤버 변수를 썼을 때 .으로 멤버 변수에 접근할 수 있음

ex. 맨 마지막 줄에서 format(self.name -> wraith1.name) 이런식으로 

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))
        
wraith2=unit("빼앗은 레이스",80,5)
wraith2.clocking=True

if wraith2.clocking==True:
    print("{0}는 현재 클로킹 상태입니다.".format(wraith2.name))
빼앗은 레이스유닛이 생성되었습니다.
체력80, 공격력5
빼앗은 레이스는 현재 클로킹 상태입니다. #wraith2.clocking = true이라는 변수 생성 후 if문으로 

2.객체에 새로운 변수를 외부에서 만들어서 사용 가능. (확장 가능!), 확장을 한 객체에 대해서만 적용됨.

ex. 두 번째 문단에서 wraith2.clocking


메소드(유닛 안의 여러개의 함수)

-클래스 attackunit 안에서 attack함수와 damaged 함수를 메소드로 사용

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))

#공격 유닛
class attackunit:
    def __init__(self,name,hp,damage): #self. 을 통해서 변수에 접근
        self.name=name
        self.hp=hp
        self.damage=damage

    def attack(self,location): #공격함수, 메소드 앞에서 무조건 self 적기
        print("{0}:{1}방향으로 적군을 공격 합니다.[공격력 {2}] "\
            .format(self.name,location,self.damage)) 
            #location은 전달받은 값쓴다. 그 외 self.name, 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("5시") #self 안보내도 됨

#공격 2번 받는다고 가정
firebat1.damaged(25)   
firebat1.damaged(25)
파이어뱃:5시방향으로 적군을 공격 합니다.[공격력 16]  #firebat1. attackunit("파이어뱃",50,16) 결과
파이어뱃:25 데미지를 입었습니 다. #firebat1.damaged(25) 결과
파이어뱃:현재 체력은 25입니다
파이어뱃:25 데미지를 입었습니 다. #firebat1.damaged(25) 결과
파이어뱃:현재 체력은 0입니다
파이어뱃:파괴되었습니다 #def damaged 메소드 안에서 if self.hp<=0인 경우 결과