PYTHON · 객체지향
프로토콜 클래스 활용
Protocol로 구조적 서브타이핑(덕 타이핑)을 타입 시스템에서 지원합니다. 상속 없이 인터페이스를 정의합니다.
객체지향고급Protocol프로토콜덕 타이핑구조적 타이핑
핵심 설명
Protocol로 구조적 서브타이핑(덕 타이핑)을 타입 시스템에서 지원합니다. 상속 없이 인터페이스를 정의합니다.
Python code
from typing import Protocol, runtime_checkable
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> str: ...
@runtime_checkable
class Resizable(Protocol):
def resize(self, factor: float) -> None: ...
# Protocol을 상속하지 않아도 호환
class Circle:
def __init__(self, r: float):
self.r = r
def draw(self) -> str:
return f"Circle(r={self.r})"
def resize(self, factor: float):
self.r *= factor
class Text:
def __init__(self, content: str):
self.content = content
def draw(self) -> str:
return f"Text({self.content})"
# 타입 체크 (구조적)
def render(item: Drawable) -> None:
print(f"렌더링: {item.draw()}")
render(Circle(5)) # OK
render(Text("안녕")) # OK
# 런타임 체크
print(isinstance(Circle(1), Drawable)) # True
print(isinstance(Circle(1), Resizable)) # True
print(isinstance(Text("x"), Resizable)) # False학습 팁
@runtime_checkable을 추가하면 isinstance()로 런타임에 프로토콜 호환성을 검사할 수 있습니다.
주의할 점
runtime_checkable Protocol의 isinstance 체크는 메서드 존재만 확인하고, 시그니처는 검사하지 않습니다.
자주 묻는 질문
프로토콜 클래스 활용란 무엇인가요?
Protocol 로 구조적 서브타이핑(덕 타이핑)을 타입 시스템에서 지원합니다. 상속 없이 인터페이스를 정의합니다.
프로토콜 클래스 활용 학습 시 주의할 점은 무엇인가요?
runtime_checkable Protocol의 isinstance 체크는 메서드 존재만 확인하고, 시그니처는 검사하지 않습니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.