이러한 기능은, 다형성을 촉진하며, 일관된 코드 컨밴션을 지킬 수 있도록 도움을 줍니다.
"다형성" 이란 ?
In programming language theory and type theory, polymorphism is the use of one symbol to represent multiple different types.
In object-oriented programming, polymorphism is the provision of one interface to entities of different data types.
The concept is borrowed from a principle in biology where an organism or species can have many different forms or stages.
Wikipedia "Polymorphism (computer science)"
쉽게 설명하여, 클래스에 선언된 메서드가 상속 받은 파생 클래스에서 같은 이름으로 오버라이딩 되어 여러 형태로 동작함을 의미합니다.
전 서버작업을 하며 주로 아래와 같이 구현하여 사용하였습니다.
class BaseRepository(ABC):
def __init__(self, session: SessionFactory) -> None:
self.session = session
@property
@abstractmethod
def model(self) -> Type[Base]:
pass
@property
@abstractmethod
def create_entity(self):
pass
@property
@abstractmethod
def return_entity(self):
pass
@property
@abstractmethod
def update_entity(self):
pass
Base가 되는 service와 repository를 추상클래스로 만들고, 해당 코드 안에 기본적인 CRUD 작업들을 구현하였습니다.
해당 CRUD 작업들을 구현할때, 각각의 모델과 그에 맞는 DTO, Entity 등의 형태를 상속받아 구현하여 CRUD 작업들을 동작하게끔 구현하였습니다.
만약 구현하려는 하위 repository 코드에서 아래와 같이 해당 내용을 구현하지 않는다면(create entitiy),
class TempRepository(BaseRepository):
def __init__(self, session: SessionFactory) -> None:
self.session = session
@property
def model(self):
return TempModel
@property
def return_entity(self):
return TempEntity
@property
def update_entity(self):
return TempEntity
아래와 같은 에러를 출력하게 됩니다.
TypeError: Can't instantiate abstract class FoodListRepository without an implementation for abstract method 'create_entity'