程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python dataclasses

編輯:Python

Here are dataclass Changes brought about by decorators :

  1. There is no need to define __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
  2. We predefined member properties in a more readable way , And type tips . We can know immediately now 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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved