Here are dataclass
Changes brought about by decorators :
__init__
, Then assign the value to self
,dataclass
Be responsible for handling it (LCTT Translation notes : The original text here may be incorrect , Mention a nonexistent d
)val
yes int
type . This is undoubtedly more readable than the general way of defining class members .from dataclasses import dataclass
@dataclass
class InventoryItem:
name:str
uint_price:float
quantity_on_hand:int=0
def total_cost(self) -> float:
return self.uint_price * self.quantity_on_hand
class InventoryItem2:
def __init__(self,name:str,uint_price:float,quantity_one_hand:int=0):
self.name = name
self.uint_price = uint_price
self.quantity_one_hand = quantity_one_hand
def total_cost(self) -> float:
return self.uint_price * self.quantity_one_hand
if __name__ == '__main__':
init = InventoryItem(name="yunshan",uint_price=12.3,quantity_on_hand=1)
print(init.name)
print(init.total_cost())
init2 = InventoryItem2(name="yunshan2",uint_price=12.3,quantity_one_hand=1)
print(init2.name)
print(init2.total_cost())
>>>
yunshan
12.3
yunshan2
12.3