추상 클래스(Abstract Base Class)

Jihun Kim·2022년 4월 15일
0

파이썬

목록 보기
10/11
post-thumbnail

추상 클래스(Abstract Base Class)

  • 공통 특성을 가진 부모 클래스이다.
  • 추상 클래스는 클래스의 메소드를 상속 받는 자식 클래스에게 특정 메소드의 구현을 강제하기 위해 사용 된다.
  • 해당 클래스는 객체 인스턴스를 생성할 수 없다.

사용하기

  • 아래와 같이 abc 모듈에서 ABCMeta, abstractmethod를 임포트 한다.
from abc import ABCMeta
from abc import abstractmethod
  • 추상 클래스는 임포트 한 abstractmethod를 데코레이터로 가진 1개 이상의 abstract method를 가져야 한다.

아래와 같이 레시피를 추상 클래스로 만들어 보겠다.

추상 클래스

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']"


참고

profile
쿄쿄

0개의 댓글