資料類別(dataclasses)

Python 的資料型別

Jason Myers

Instructor

為什麼用 dataclasses

  • 支援預設值
  • 自訂物件顯示
  • 輕鬆轉為 tuple 或字典
  • 自訂屬性
  • 鎖定(凍結)實例
Python 的資料型別

第一個 dataclass 範例

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 的資料型別

輕鬆轉為 tuple 或字典

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 的資料型別

鎖定(Frozen)實例

@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...