在写代码过程中,我们经常需要创建一些简单的类来存储数据。传统方式需要手动编写__init__
、__repr__
、__eq__
等方法,不仅繁琐还容易出错。直到引入的dataclasses
模块。
安装
Python 3.6,可以通过pip安装:
pip install dataclasses
【3.7 +的内置模块,无需安装即可使用】
基本用法
from dataclasses import dataclass @dataclass class Book: title: str author: str price: float pages: int = 0 book = Book("python", "Lowen", 99) print(book) #Book(title='python', author='Lowen', price=99, pages=0) print(book.title) #python print(book.author) #Lowen print(book.price) #99 print(book.pages) #0
只需要添加@dataclass
装饰器,就自动获得了:
- 初始化方法
- 字符串表示
- 比较方法
- 可选的默认值支持
高级用法
from dataclasses import dataclass, field, asdict, replace @dataclass(frozen=True) # 创建不可变类 class Point: x: float y: float # 使用field自定义字段属性 coordinates: tuple = field(default_factory=tuple, repr=False) # 不可变对象 p1 = Point(3, 4) p11 = Point(3, 4, (4,)) print(p1) # Point(x=3, y=4) print(p11.coordinates[0]) # 4 # p11.x = 5 # 这会引发错误 # 转换为字典 point_dict = asdict(p1) print(point_dict) # {'x': 3, 'y': 4, 'coordinates': ()} # 创建对象的修改副本 p2 = replace(p1, x=5) print(p2) # Point(x=5, y=4)
实战用法
from dataclasses import dataclass, field from typing import List from decimal import Decimal @dataclass class Product: name: str price: Decimal quantity: int = 0 @dataclass class ShoppingCart: items: List[Product] = field(default_factory=list) def add_item(self, product: Product): self.items.append(product) @property def total(self) -> Decimal: return sum(item.price * item.quantity for item in self.items) # 使用示例 cart = ShoppingCart() cart.add_item(Product("Python书籍", Decimal("49.9"), 2)) cart.add_item(Product("键盘", Decimal("299"), 1)) print(f"购物车总价: ¥{cart.total}")
来源链接:https://www.cnblogs.com/pywen/p/18676918
没有回复内容