B16 - data classes
sources: python docs, ArjanCodes
- module providing decorator and functions for automatically adding generated special methods
from dataclasses import dataclass
@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
- here, the above code will automatically add:
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
@dataclassexamines the class to findfields, class variables with type annotations- in the above code,
name,unit_priceandquantity_on_handare thefields - default values may be specified, like for
quantity_on_hand
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
match_args=True, kw_only=False, slots=False, weakref_slot=False)
-
the decorator adds various 'dunder' methods
-
by defaults, the following are added:
__init____repr____eq____match_args__
-
orderuses the first field to sort the data
from dataclasses import dataclass, field
@dataclass(order =True)
class Student:
sort_index : int = field(init=False)
name: str
grade: int
roll_num: int
def __post_init__(self):
self.sort_index = self.age
- here, using the
fieldfunction withinit = False, it sets the value of the sorting index later, so it doesn't need to be passed when defining an object