Subtype in Python

Subtype

subtype은 파이썬 기본 type(또는 기존 클래스)에서 파생된 type입니다.

저는 subtype을 예제를 통해서 쉽게 이해할 수 있었는데요.

class PositiveInt(int):
    def __new__(cls, value: int) -> "PositiveInt":
        if value < 0:
            raise ValueError("양수만 입력 가능")
        return super().__new__(cls, value)

x = PositiveInt(4)
# y = PositiveInt(-1) # 에러 발생

print(x) # 4

이 예제처럼 'PositiveInt'클래스가 내장 타입인 int 타입의 subtype입니다.

예제는 'PositivieInt'클래스는 int 타입을 상속받고, 새 인스턴스를 생성하는 dunder 메서드인 'new'에서 음수 인경우 ValueError를 일으키고 음수 일경우 parent 클래스인 int클래스의 'new' 메서드를 상속 받아 매개변수로 입력받은 value를 대입합니다.

다른 예제를 더 살펴보겠습니다.

class PositiveIntList(list):
    def append(self, value: int) -> None:
        if value < 0:
            raise ValueError("양수가 아닙니다.")
        super().append(value)


class Int0to10List(PositiveIntList):
    def append(self, value: int) -> None:
        if value > 10:
            raise ValueError("10보다 큽니다.")
        super().append(value)


my_positive_list: PositiveIntList = PositiveIntList()
my_positive_list.append(4)
# my_positive_list.append(-5)   # ValueError: 양수가 아닙니다.
print(my_positive_list) # [4]

my_0to10_list: Int0to10List = Int0to10List()
my_0to10_list.append(1)
# my_0to10_list.append(100) # ValueError: 10보다 큽니다.
# my_0to10_list.append(-10) # ValueError: 양수가 아닙니다.
print(my_0to10_list)    # [1]

이 예제에서 'PositiveIntList'클래스는 'list'클래스의 subtype이고, 'Int0to10List'는 'PositiveIntList'의 subtype입니다.

다시 subtype을 설명하면 상위 타입(위의 예제에서는 PositiveIntList)이나 기본 타입(위의 예제에서는 list)에서 파생된 타입으로, subtype에서는 상위 타입의 모든 특성과 동작을 상속해 고유한 특성이나 동작을 추가할 수도 있습니다.

 

 

 

 


부족하거나 잘못된 내용이 있을 경우 댓글 달아주시면 감사하겠습니다.

이 글에 부족한 부분이 존재할 경우 추후에 수정될 수 있습니다.


 

'Python > Python' 카테고리의 다른 글

Python 라이브러리 - textwrap  (1) 2023.05.10
Python에서의 캡슐화  (0) 2023.04.28
First Class Function  (0) 2023.03.30
파이썬에서 Function과 method의 차이  (0) 2023.03.20
Python 에서의 Lambda method  (0) 2023.02.22