class Unit:
    """
    인스턴스 속성 : 이름, 체력, 방어막, 공격력
    -> 객체마다 다른 값을 가지는 속성
    
    클래스 속성 : 전체 유닛 개수
    -> 모든 객체가 공유하는 속성

    비공개 속성
    -> 클래스안에서만 사용 가능한 속성
    """
    count = 0
    # 매직 메서드
    # 클래스 안에서 정의 할 수 있는 스페셜 메서드
    # __이름__으로 구성
    def __init__(self, name, hp, shield, damage):
        # 인스턴스 속성은 클래스 안에서 self.속성명
        self.name = name
        # 비공개 속성은 클래스 안에서 self.__속성명
        self.hp = hp
        self.shield = shield
        self.damage = damage
        # 클래스 속성은 객체명.속성명
        Unit.count += 1
        print(f"[{self.name}](이)가 생상 되었습니다.")

    def __str__(self):
        return f"[{self.name}] 체력 : {self.hp} 방어막 : {self.shield} 공격력 : {self.damage}"

    # 인스턴스 메서드 추가 (instance method)
    # 인스턴스 속성에 접근할 수 있는 메서드
    # 항상 첫번째 파라미터로 self를 갖는다
    def hit(self, damage):
        # 1. 방어막 변경 먼저
        if self.shield >= damage:
            self.shield -= damage
            damage = 0
        else:
            damage -= self.shield
            self.shield = 0
        
        # 2. 체력 변경
        if damage > 0:
            if self.hp > damage:
                self.hp -= damage
            else:
                self.hp = 0

    # 클래스 메서드
    # 클래스 속성에 접근하기 위해서 사용한다.
    # 클래스를 의미하는 cls를 파라미터로 받는다.
    @classmethod
    def print_count(cls):
        print(f"생성된 유닛 개수 : [{cls.count}]개")
        # cls = 현재 클래스 
        # cls.count = Unit.count           

probe = Unit("프로브", 20, 20, 5)
zealot = Unit("질럿", 100, 60, 16)
dragoon = Unit("드라군", 100, 80, 20)

probe.hit(16)
print(probe)
probe.hit(16)
print(probe)
probe.hit(16)
print(probe)

Unit.print_count()

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

BELATED ARTICLES

more