ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python] 클래스
    python 2025. 5. 28. 10:28

    클래스

    Python의 클래스(class)는 데이터(속성)와 기능(메서드)을 하나로 묶는 틀(blueprint)입니다.

    서로 연관이 있는 변수와 함수의 집합!

     

    🐟 클래스는 붕어빵 틀이에요!

    • 붕어빵 틀은 모양이 정해져 있죠? (생김새, 내용물 등)
    • 이 틀을 이용해서 붕어빵(객체)을 여러 개 만들 수 있어요.
    • 붕어빵마다 이 들 수도 있고, 슈크림이 들 수도 있죠.

     

    🧠 개념 정리 (붕어빵 버전)

    class 붕어빵 틀 (설계도)
    object 붕어빵 (틀로 찍은 결과물)
    속성(attribute) 붕어빵의 내용물 (팥, 슈크림 등)
    메서드(method) 붕어빵이 하는 행동 (예: 먹힌다, 포장된다 등)
    __init__ 붕어빵을 만들 때 반죽 넣고 굽는 과정
    self 붕어빵 자신

     

    🔹 기본 구조

    class ClassName:
        def __init__(self, parameter1, parameter2):
            self.attribute1 = parameter1
            self.attribute2 = parameter2
    
        def method_name(self):
            # 기능 구현
            print(self.attribute1, self.attribute2)

     

    🔹 예제: 간단한 사람 클래스

    class Person:
        def __init__(self, name, age):
            self.name = name      # 속성(attribute)
            self.age = age
    
        def greet(self):          # 메서드(method)
            print(f"Hello, my name is {self.name} and I am {self.age} years old.")
    # 객체 생성
    p1 = Person("Alice", 30)
    p1.greet()   # 출력: Hello, my name is Alice and I am 30 years old.

     

    🔹 주요 용어 정리

    class 클래스 정의 키워드
    __init__ 생성자(constructor), 객체 생성 시 자동 호출
    self 인스턴스 자신을 가리키는 예약어 (속성/메서드 접근용)
    속성(attribute) 객체가 가지는 데이터 (예: 이름, 나이)
    메서드(method) 객체가 수행할 수 있는 함수 (예: 인사하기)

     

    🔹 클래스의 장점

    • 코드 재사용성 ↑ (같은 구조로 여러 객체 생성 가능)
    • 유지보수성 ↑ (기능 분리 및 확장 용이)
    • 현실 세계 모델링에 유리

     

    실습 (Class 미사용)

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


    마린 유닛이 생성되었습니다.
    체력 40, 공격력 5

     

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

     

     

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

     

    tank2_name = "탱크"
    tank2_hp = 150
    tank2_damage = 35
    
    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)

     

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

     

    실습 (Class 사용)

    class Unit:
        def __init__(self, name, hp, damage):
            self.name = name # 멤버변수 1
            self.hp = hp # 멤버변수 2
            self.damage = damage # 멤버변수 3
            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)

     

    마린 유닛이 생성되었습니다.
    체력 40, 공격력 5
    마린 유닛이 생성되었습니다.
    체력 40, 공격력 5
    탱크 유닛이 생성되었습니다.
    체력 150, 공격력 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))
    
    # 레이스 : 공중 유닛, 비행기, 클로킹 (상대방에게 보이지 않음)
    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))

     

    레이스 유닛이 생성되었습니다.
    체력 80, 공격력 5
    유닛 이름 : 레이스, 공격력 : 5
    빼앗은 레이스 유닛이 생성되었습니다.
    체력 80, 공격력 5
    빼앗은 레이스는 현재 클로킹 상태입니다.

    'python' 카테고리의 다른 글

    [python] 상속  (0) 2025.05.28
    [python] 메소드  (0) 2025.05.28
    [python] with  (1) 2025.05.27
    [python] pickle  (0) 2025.05.27
    [python] 파일 입출력  (0) 2025.05.27
Designed by Tistory.