dataclasses
提供一个装饰器,自动生产init 和 repr
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
#等价于下面所示代码
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
dataclasses.dataclass用法
下示三种用法作用是相同的
@dataclass
class C:
...
@dataclass()
class C:
...
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False)
class C:
...
如果frozen =True 则属性不可赋值
dataclasses.field用法
dataclasses.asdict 用法
将dataclass实例转化为字典
@dataclass
class Point:
x: int
y: int
@dataclass
class C:
mylist: list[Point]
p = Point(10, 20)
assert asdict(p) == {'x': 10, 'y': 20}
c = C([Point(0, 0), Point(10, 4)])
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
dataclasses.astuple 用法
将dataclass实例转化为元组
@dataclass
class Point:
x: int
y: int
@dataclass
class C:
mylist: list[Point]
p = Point(10, 20)
assert astuple(p) == (10, 20)
c = C([Point(0, 0), Point(10, 4)])
assert astuple(c) == ([(0, 0), (10, 4)],)