[python] class 생성, 상속

덴장·2024년 9월 13일

python

목록 보기
27/30

class Unit:
def init(self, name, hp ): #python의 생성자 init
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): #python의 생성자 init
Unit.init(self , name, hp) # 클래스 상속
#self.name = name # 멤버변수
#self.hp = hp # 멤버변수
self.damage = damage # 멤버변수

    ## 멤버변수 - 클래스 내 생성된 변수
    print("{0} 유닛이 생성되었습니다.".format(self.name))
    print("체력 {0}, 공격력 {1}".format(self.hp, self.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 , damage)
Flyable.init(self , flying_speed )

############################################################################
marine1 = AttackUnit("마린" , 40 , 5)
marine2 = AttackUnit("마린" , 40 , 5)
tank1 = AttackUnit("탱크" , 150 , 35)

#생성
wraith1 = AttackUnit("레이스" , 80 , 5) # 외부에서 멤버변수 접근
print("유닛이름 : {0} , 공격력 : {1}".format(wraith1.name , wraith1.damage))

#생성
wraith2 = AttackUnit("뻬앗은 레이스" , 80 , 5) # 외부에서 멤버변수 접근
wraith2.clocking = True # 외부에서 멤버변수를 추가로 할당함. 이 생성자에만 존재함. 예를들어 wraith1 엔 clocking 이 없음

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

#유닛 생성
firebat1 = AttackUnit("파이어뱃" , 50 , 16)
firebat1.attack("5시")

#데미지입음
firebat1.damaged(25)
firebat1.damaged(25)

#다중상속 유닛생성
valkyrie = FlyableAttackUnit("발키리" , 200 , 6,5)
valkyrie.fly(valkyrie.name,"5시")

profile
개발자

0개의 댓글