데이터클래스

Python의 데이터 타입

Jason Myers

Instructor

왜 데이터클래스를 쓰나요

  • 기본값 지원
  • 사용자 지정 객체 표현
  • 튜플/딕셔너리로 손쉽게 변환
  • 사용자 지정 프로퍼티
  • 동결된 인스턴스
Python의 데이터 타입

첫 데이터클래스 살펴보기

from dataclasses import dataclass
@dataclass
class Cookie:
    name: str
    quantity: int = 0
chocolate_chip = Cookie("chocolate chip", 13)
print(chocolate_chip.name)
print(chocolate_chip.quantity)
chocolate chip
13
Python의 데이터 타입

튜플/딕셔너리로 손쉬운 변환

from dataclasses import asdict, astuple

ginger_molasses = Cookie("ginger molasses", 8)
asdict(ginger_molasses)
{'name': 'ginger molasses', 'quantity': 8}
astuple(ginger_molasses)
('ginger molasses', 8)
Python의 데이터 타입

사용자 지정 프로퍼티

from decimal import Decimal


@dataclass
class Cookie:
    name: str
    cost: Decimal
    quantity: int
   @property
   def value_of_goods(self):
      return int(self.quantity) * self.cost
Python의 데이터 타입

프로퍼티 사용 예

peanut = Cookie("peanut butter", Decimal("1.2"), 8)

peanut.value_of_goods
Decimal('9.6')
Python의 데이터 타입

동결된 인스턴스

@dataclass(frozen=True)
class Cookie:
    name: str
    quantity: int = 0

c = Cookie("chocolate chip", 10)
c.quantity = 15
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'quantity'
Python의 데이터 타입

연습해 봅시다!

Python의 데이터 타입

Preparing Video For Download...