PHpullh
학습 라이브러리/Python/상속 & ABC & Protocol

PYTHON · 객체지향

상속 & ABC & Protocol

다형성을 구현하는 세 가지 방법: 상속, 추상 기반 클래스(ABC), 구조적 서브타이핑(Protocol).

객체지향중급ABCabstractmethodProtocol상속super

핵심 설명

다형성을 구현하는 세 가지 방법: 상속, 추상 기반 클래스(ABC), 구조적 서브타이핑(Protocol).

Python code

from abc import ABC, abstractmethod
from typing import Protocol, runtime_checkable

# 추상 기반 클래스 (ABC)
class Animal(ABC):
    def __init__(self, name: str):
        self.name = name

    @abstractmethod
    def sound(self) -> str: ...

    def describe(self):   # 공통 구현
        print(f"{self.name}는 {self.sound()} 합니다")

class Dog(Animal):
    def sound(self) -> str: return "멍멍"

class Cat(Animal):
    def sound(self) -> str: return "야옹"

# Protocol — 구조적 서브타이핑 (duck typing 공식화)
@runtime_checkable
class Drawable(Protocol):
    def draw(self) -> None: ...

class Circle:   # Drawable을 명시적으로 상속하지 않음
    def draw(self): print("⭕ 원 그리기")

class Square:
    def draw(self): print("⬜ 사각형 그리기")

def render(shape: Drawable):
    shape.draw()

# super() 활용
class Vehicle:
    def __init__(self, brand: str):
        self.brand = brand

class ElectricCar(Vehicle):
    def __init__(self, brand: str, battery: int):
        super().__init__(brand)
        self.battery = battery

Dog("Rex").describe()          # Rex는 멍멍 합니다
render(Circle())               # ⭕ 원 그리기
print(isinstance(Circle(), Drawable))  # True

학습 팁

Protocol은 명시적 상속 없이도 "그 메서드를 구현하면 그 타입"으로 취급합니다. Go의 interface와 유사한 구조적 타이핑입니다.

주의할 점

ABC를 상속하고 @abstractmethod를 구현하지 않으면 인스턴스 생성 시 TypeError가 발생합니다.

자주 묻는 질문

상속 & ABC & Protocol란 무엇인가요?

다형성을 구현하는 세 가지 방법: 상속, 추상 기반 클래스(ABC), 구조적 서브타이핑(Protocol).

상속 & ABC & Protocol 학습 시 주의할 점은 무엇인가요?

ABC 를 상속하고 @abstractmethod 를 구현하지 않으면 인스턴스 생성 시 TypeError 가 발생합니다.