概括
我有dataclass10多个字段。print()使用它们将有趣的上下文埋藏在默认值的墙中 - 让我们通过不再不必要地重复这些来使它们变得更友好。
Python 中的数据类
Python 的@dataclasses.dataclass()( PEP 557 ) 提供自动可打印表示 ( __repr__())。
假设这个例子,基于 python.org 的:
from dataclasses import dataclass
@dataclass
class InventoryItem:
name: str
unit_price: float = 1.00
quantity_on_hand: int = 0
Run Code Online (Sandbox Code Playgroud)
装饰器@dataclass(repr=True)(默认)将得到print()一个很好的输出:
InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
Run Code Online (Sandbox Code Playgroud)
我想要的:跳过打印默认值
repr它会打印所有字段,包括您不想显示的隐含默认值。
print(InventoryItem("Apple"))
# Outputs: InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
# I want: InventoryItem(name='Apple')
Run Code Online (Sandbox Code Playgroud)
print(InventoryItem("Apple", unit_price="1.05"))
# Outputs: InventoryItem(name='Apple', unit_price='1.05', quantity_on_hand=0)
# I want: InventoryItem(name='Apple', unit_price='1.05') …Run Code Online (Sandbox Code Playgroud)