Learning
레슨 5 / 9·20분

클래스와 객체지향 프로그래밍

클래스 기초

Python은 객체지향 프로그래밍(OOP)을 지원합니다. class 키워드로 클래스를 정의하고, __init__ 메서드로 초기화합니다. self는 인스턴스 자신을 가리킵니다.

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

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

    def bark(self):
        return self.name + ": 멍멍!"

    def info(self):
        return self.name + " (" + str(self.age) + "살)"

# 인스턴스 생성
dog1 = Dog("바둑이", 3)
dog2 = Dog("초코", 5)

print(dog1.bark())  # 바둑이: 멍멍!
print(dog2.info())  # 초코 (5살)
print(Dog.species)  # 개

상속과 다형성

상속을 통해 기존 클래스를 확장할 수 있습니다. 자식 클래스는 부모 클래스의 속성과 메서드를 물려받으며, 메서드 오버라이딩으로 동작을 변경할 수 있습니다.

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

    def speak(self):
        raise NotImplementedError("하위 클래스에서 구현하세요")

    def __str__(self):
        return "Animal: " + self.name

class Cat(Animal):
    def speak(self):
        return self.name + ": 야옹~"

class Duck(Animal):
    def speak(self):
        return self.name + ": 꽥꽥!"

# 다형성 - 같은 인터페이스, 다른 동작
animals = [Cat("나비"), Duck("도널드")]
for animal in animals:
    print(animal.speak())
# 나비: 야옹~
# 도널드: 꽥꽥!

특수 메서드 (매직 메서드)

python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return "Vector(" + str(self.x) + ", " + str(self.y) + ")"

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __len__(self):
        return int((self.x ** 2 + self.y ** 2) ** 0.5)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2

print(v3)        # Vector(4, 6)
print(v1 == v2)  # False
print(len(v2))   # 5
  • __init__ -- 생성자, 인스턴스 초기화
  • __str__ -- print() 시 출력 문자열
  • __repr__ -- 개발용 문자열 표현
  • __add__, __sub__ -- 연산자 오버로딩
  • __eq__, __lt__ -- 비교 연산자 정의
  • super() -- 부모 클래스 메서드 호출
💡

Python은 다중 상속을 지원하지만, 복잡도가 높아지므로 되도록 단일 상속과 믹스인(Mixin) 패턴을 사용하세요.