Programming Languages/Python

추상 클래스와 인터페이스

newclass 2025. 3. 26. 04:08

추상 클래스와 인터페이스

1. 추상 클래스(Abstract Class)

추상 클래스는 직접 인스턴스화할 수 없고, 다른 클래스가 상속받아 구현해야 하는 메서드를 정의하는 클래스입니다. 파이썬에서는 abc 모듈을 사용하여 추상 클래스를 구현합니다.

from abc import ABC, abstractmethod

class Animal(ABC):  # ABC를 상속받아 추상 클래스 생성
    
    @abstractmethod  # 추상 메서드 정의
    def make_sound(self):
        pass  # 구현은 자식 클래스에서
    
    @abstractmethod
    def move(self):
        pass
    
    def breathe(self):
        return "숨을 쉽니다."  # 일반 메서드 (기본 구현 제공)

class Dog(Animal):
    def make_sound(self):
        return "멍멍"
    
    def move(self):
        return "뛰어다닙니다."

class Fish(Animal):
    def make_sound(self):
        return "..."  # 물고기는 소리를 내지 않지만 메서드는 구현해야 함
    
    def move(self):
        return "헤엄칩니다."

# 추상 클래스는 인스턴스화할 수 없음
try:
    animal = Animal()  # TypeError 발생
except TypeError as e:
    print(f"오류 발생: {e}")

# 구체 클래스는 인스턴스화 가능
dog = Dog()
fish = Fish()

print(dog.make_sound())  # 출력: 멍멍
print(fish.move())       # 출력: 헤엄칩니다.
print(dog.breathe())     # 출력: 숨을 쉽니다.

2. 인터페이스(Interface)

파이썬은 공식적으로 인터페이스를 지원하지 않지만, 추상 클래스와 추상 메서드를 사용하여 인터페이스와 유사한 기능을 구현할 수 있습니다.

from abc import ABC, abstractmethod

# 인터페이스처럼 사용할 추상 클래스
class Drawable(ABC):
    @abstractmethod
    def draw(self):
        pass

class Resizable(ABC):
    @abstractmethod
    def resize(self, width, height):
        pass

# 여러 인터페이스 구현
class Rectangle(Drawable, Resizable):
    def __init__(self, width, height):
        self.width = width
        self.height = height
    
    def draw(self):
        return f"사각형 그리기 (너비: {self.width}, 높이: {self.height})"
    
    def resize(self, width, height):
        self.width = width
        self.height = height
        return f"크기 조정 - 새 너비: {self.width}, 새 높이: {self.height}"

# 사용 예
rect = Rectangle(10, 20)
print(rect.draw())
print(rect.resize(30, 40))
print(rect.draw())