ABCMeta
, abstractmethod
를 임포트 한다.from abc import ABCMeta
from abc import abstractmethod
아래와 같이 레시피를 추상 클래스로 만들어 보겠다.
class Recipe(metaclass=ABCMeta): # 추상 클래스는 ABCMeta를 상속 받아야 한다.
def __init__(self):
self.my_ingredients = []
def wash_hands(self, has_washed): # 손을 반드시 씻어야 한다.
return has_washed
@abstractmethod
def prepare(self): # Recipe 클래스를 상속 받는 모든 클래스는 prepare 메소드를 오버라이딩 해야 한다.
raise NotImplementedError()
Recipe 추상 클래스는 인스턴스화가 불가능 하다.
만약 추상 클래스에 구현 내용은 없고 구현해야 하는 메소드들만 나열 했다면 해당 추상 클래스는 인터페이스라고도 부를 수 있다.
이제 Recipe 추상 클래스를 상속 받는 자식 클래스를 만들어 다형성을 구현할 수 있다.
자식 클래스(BeefStaek)
class BeefStaek(Recipe):
def prepare(self, beef):
if self.wash_hands():
self.my_ingredients.append(beef)
else:
pass
def __str__(self):
return f"Beef staek made with: {self.my_ingredients}"
실행
beef_staek = BeefStaek() # 인스턴스화
print(beef_staek) # "Beef staek made with: []"
beef_staek.wash_hands(has_washed=True) # 손을 씻는다.
beef_staek.prepare(beef='beef') # 재료를 추가해 확인하기
print(beef_staek) # "Beef staek made with: ['beef']"
참고