Dataclass

Tipe Data di Python

Jason Myers

Instructor

Mengapa menggunakan dataclass

  • Dukungan nilai default
  • Representasi objek kustom
  • Konversi mudah ke tuple atau dictionary
  • Properti kustom
  • Instance beku
Tipe Data di Python

Melihat dataclass pertama kita

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
Tipe Data di Python

Konversi mudah ke tuple atau dictionary

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)
Tipe Data di Python

Properti kustom

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
Tipe Data di Python

Menggunakan properti kustom

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

peanut.value_of_goods
Decimal('9.6')
Tipe Data di Python

Instance beku

@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'
Tipe Data di Python

Ayo berlatih!

Tipe Data di Python

Preparing Video For Download...