개발언어 Back-End/Python

python에서 클래스의 인터페이스를 구현하는 방법

bluebamus 2025. 3. 11.

기반 자료 : https://puddingcamp.com/page/3634ccee-010c-4d4d-992f-c5cb52490ed4

 

1. 문제 정의

   - user 클래스를 만드는데 BaseUser를 사용하는 것을 확인하고 했다.

   - 나의 예상은 Django와 비슷하게 사전에 정의된 모델이 있지 않을까 생각했다.

from pydantic import BaseModel
from starlette.authentication import BaseUser


class User(BaseUser, BaseModel):
    username: str
    password: str

    @property
    def is_authenticated(self) -> bool:
        return True

    @property
    def display_name(self) -> str:
        return self.username

    @property
    def identity(self) -> str:
        return self.username

 

2. BaseUser 클래스의 분석

   - BaseUser는 인터페이스만 있는 일관성을 유지하기 위한 구조 클래스였다.

class BaseUser:
    @property
    def is_authenticated(self) -> bool:
        raise NotImplementedError()  # pragma: no cover

    @property
    def display_name(self) -> str:
        raise NotImplementedError()  # pragma: no cover

    @property
    def identity(self) -> str:
        raise NotImplementedError()  # pragma: no cover

 

3. 다른 클래스들에서 BaseUser를 사용하는 방법

class BaseUser:
    @property
    def is_authenticated(self) -> bool:
        raise NotImplementedError()  # pragma: no cover

    @property
    def display_name(self) -> str:
        raise NotImplementedError()  # pragma: no cover

    @property
    def identity(self) -> str:
        raise NotImplementedError()  # pragma: no cover


class SimpleUser(BaseUser):
    def __init__(self, username: str) -> None:
        self.username = username

    @property
    def is_authenticated(self) -> bool:
        return True

    @property
    def display_name(self) -> str:
        return self.username


class UnauthenticatedUser(BaseUser):
    @property
    def is_authenticated(self) -> bool:
        return False

    @property
    def display_name(self) -> str:
        return ""

 

4. 정리

   - 해당 코드를 정리하게 된 이유가, 일반적으로 파이썬에서는 인터페이스 구현이 불가하기 때문에, 추상화 클래스를 사용하여 인터페이스라 칭하는 경우가 대부분의 예시였다.

   - 하지만 이렇게 인터페이스 클래스의 속성에 에러를 정의함으로, 재정의 하지 않으면 에러가 뜨기 때문에 반드시 오버라이딩 하도록 규정한다면 인터페이스의 형태를 제공할 수 있는 좋은 방법이라 생각이 되었다.

 

5. 인터페이스 사용의 장점

   5.1. 일관성 보장

      -  모든 자식 클래스가 반드시 동일한 속성이나 메서드를 구현해야 함.
      - 팀원 간 규칙을 강제할 수 있어 코드 품질이 높아짐.

 

   5. 2. 다형성(Polymorphism) 지원

      - 인터페이스 타입으로 다양한 자식 클래스 인스턴스를 처리 가능.

      - BaseUser 타입 하나로 SimpleUser, AdminUser, UnauthenticatedUser 등 다양한 객체를 일관성 있게 다룰 수 있음.

 

   5. 3. 코드 확장성 증가

      - 새로운 클래스가 추가되어도 기존 코드를 수정할 필요가 없음(OCP 원칙 준수).

      - 공통 인터페이스 덕분에 시스템 확장이 쉬움.

 

   5. 4. 타입 안정성과 가독성 향상

      - 명확한 타입 힌트 제공 (def func(user: BaseUser) 형태).

      - 개발자와 코드 리뷰어가 객체의 역할과 구조를 빠르게 이해할 수 있음.

 

   5. 5. 유지보수성 향상

      - 변경이 필요한 경우 인터페이스만 보면 어디를 고쳐야 하는지 명확.

      - 중복 코드 최소화, 공통 규칙 관리가 쉬움.

댓글