dataclasses — 数据类

源代码: Lib/dataclasses.py


此模块提供装饰器和函数为自动添加生成的 special methods 譬如 __init__() and __repr__() 到用户定义类。它的最初描述在 PEP 557 .

在这些生成的方法中使用的成员变量的定义是使用 PEP 526 类型注解。例如,此代码:

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