Python 클래스

클래스 정의

class Dog:
    # 클래스 변수 (모든 인스턴스 공유)
    species = "Canis"

    # 생성자
    def __init__(self, name, age):
        self.name = name    # 인스턴스 변수
        self.age = age

    # 인스턴스 메서드
    def bark(self):
        return f"{self.name}: 멍멍!"

dog = Dog("바둑이", 3)
dog.bark()              # "바둑이: 멍멍!"

메서드 종류

class MyClass:
    count = 0

    def __init__(self, value):
        self.value = value
        MyClass.count += 1

    # 인스턴스 메서드: self로 인스턴스 접근
    def instance_method(self):
        return self.value

    # 클래스 메서드: cls로 클래스 접근
    @classmethod
    def class_method(cls):
        return cls.count

    # 정적 메서드: 클래스/인스턴스 접근 안함
    @staticmethod
    def static_method(x, y):
        return x + y

상속

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        raise NotImplementedError

class Cat(Animal):
    def speak(self):
        return f"{self.name}: 야옹"

class Dog(Animal):
    def speak(self):
        return f"{self.name}: 멍멍"

# 다중 상속
class Hybrid(Cat, Dog):
    pass

# 부모 클래스 호출
class Child(Parent):
    def __init__(self, name, extra):
        super().__init__(name)
        self.extra = extra

오버라이딩

# 오버라이딩 (Overriding): 부모 메서드 재정의
class Animal:
    def speak(self):
        return "소리"

class Dog(Animal):
    def speak(self):          # 부모 메서드 덮어씀
        return "멍멍"

Dog().speak()  # "멍멍"

자주 쓰는 특수 메서드

__init__(self)      # 생성자
__del__(self)       # 소멸자
__repr__(self)      # 개발자용 문자열
__str__(self)       # 사용자용 문자열
__len__(self)       # len() 호출 시
__getitem__(self, key)   # obj[key]
__setitem__(self, key, value)  # obj[key] = value
__contains__(self, item)  # in 연산자
__call__(self)      # obj() 호출 가능하게
__eq__(self, other) # ==
__lt__(self, other) # <
__add__(self, other) # +
__iter__(self)      # 반복 가능하게
__enter__, __exit__ # with 문 지원