Dataclasses

Python में डेटा टाइप्स

Jason Myers

Instructor

Dataclasses क्यों इस्तेमाल करें

  • डिफॉल्ट वैल्यू का सपोर्ट
  • ऑब्जेक्ट्स की कस्टम रिप्रेजेंटेशन
  • ट्यूपल या डिक्शनरी में आसान कन्वर्ज़न
  • कस्टम प्रॉपर्टीज़
  • फ्रोज़न इंस्टेन्सेज़
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 में डेटा टाइप्स

ट्यूपल या डिक्शनरी में आसान कन्वर्ज़न

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