[python/근본] abc, ABC, abstractmethod

김진만·2024년 4월 27일
0

abc 모듈

주로 오픈소스 만들 때, 클래스 상속 시 특정 메소드 필수 구현 강요
"Cat 클래스는 speak 메소드를 정의 안해서 에러 발생" 이 부분이 제일 중요^^.

from abc import ABC, abstractmethod

class AbstractAnimal(ABC):

    @abstractmethod
    def speak(self):
        pass

class Dog(AbstractAnimal):
    def speak(self):
        return "Woof!"

class Cat(AbstractAnimal):
    def speak_test(self):
        return "Meow!"

# 추상 클래스를 상속받은 구체 클래스의 인스턴스 생성
dog = Dog()
print(dog.speak()) # 출력: Woof!

cat = Cat()
print(cat.speak_test()) # 출력: TypeError: Can't instantiate abstract class Dog with abstract method speak!

# 추상 클래스 직접 인스턴스화 시도 (오류 발생)
try:
    animal = AbstractAnimal()
except TypeError as e:
    print(e) # Cannot instantiate abstract class AbstractAnimal with abstract method speak
profile
충분한 전기와 컴퓨터 한 대와 내 이 몸만 남아 있다면 지구를 재건할 수 있습니다.

0개의 댓글