동산로의 블로그
dataclass decorator in python 본문
파이썬의 데이터 클래스 데코레이터에 대해서 알아봅시다.
dataclasses 모듈에 포함된 기능입니다. 데이터 중심 클래스를 만드는 데에 있어서 도움을 줍니다. 코드 작성시 반복적인 코드를 줄일 수 있고, 더불어 간결하고 가독성을 높은 코드를 짤 수 있습니다.
__init__()
__repr__()
, __eq__()
, __hash__()
등의 특수 메소드들을 자동으로 생성해줍니다.
order=True
를 통해서 비교 연산자 __lt__()
,__le__()
,__gt__()
,__ge__()
도 자동으로 생성해 줍니다.
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name : str
unit_price : float
quantity_on_hand : int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
예를 들어서 위의 코드를 작성하면 @dataclass
가 자동으로 다음을 추가해 줍니다.
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0 ):
self.name = name
self.unit_price = unit_price
self.quantity_on_hand = quantity_on_hand
@dataclass
는 기본값으로 설정되어 있는 값들이 있습니다. 아무 것도 입력하지 않으면 기본값이 들어가게 됩니다.
@dataclass
class C:
...
@dataclass()
class C:
...
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, math_args=True, kw_only=False, slots=False, weakref_slot=False)
class C:
...