abc#

Abstract Base Class를 정의하고 하위 클래스에 인터페이스 구현을 강제하는 Python 내장 모듈이다.

기본 사용법#

ABC를 상속받고 필수 메서드에 @abstractmethod 데코레이터를 붙인다. 추상 클래스를 직접 생성하거나 하위 클래스에서 추상 메서드를 하나라도 override하지 않으면 TypeError가 발생한다.

eg.

from abc import ABC, abstractmethod


class Storage(ABC):
    @abstractmethod
    def save(self, data: bytes) -> None:
        ...


class LocalStorage(Storage):
    def save(self, data: bytes) -> None:
        pass


# Storage() -> TypeError: Can't instantiate abstract class Storage
store = LocalStorage()

C++ 비교#

C++에서 pure virtual function을 가진 추상 클래스와 역할이 동일하며, 검증 시점에 차이가 있다.

항목C++ Pure Virtual ClassPython abc.ABC
선언 문법virtual void save() = 0;class Base(ABC): + @abstractmethod
동작 원리컴파일러 vtable 검사ABCMeta metaclass 검사
검증 시점Compile time객체 생성 시점의 Runtime
위반 시 결과컴파일 에러SubClass() 호출 시 TypeError 발생

주의사항#

ABC 상속 누락#

ABC를 상속받지 않고 @abstractmethod만 선언하면 인스턴스화가 차단되지 않는다. 반드시 두 요소를 함께 사용해야 한다.

eg.

from abc import abstractmethod


class BrokenBase:
    @abstractmethod
    def run(self) -> None:
        ...


b = BrokenBase()  # ABC 상속이 없으므로 에러 없이 생성됨

추상 프로퍼티 선언#

@property와 @abstractmethod를 함께 사용할 때는 @property를 바깥쪽에 배치한다.

eg.

from abc import ABC, abstractmethod


class Resource(ABC):
    @property
    @abstractmethod
    def name(self) -> str:
        ...