You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重写Python dataclass的默认打印输出?以InventoryItem为例

修改Python Dataclass实例的输出格式

要让InventoryItem实例被打印时输出指定格式的字符串,只需在类中自定义__str__方法即可。dataclass默认生成的__repr__方法会决定对象的默认显示内容,我们通过手动实现__str__来覆盖这个行为,得到想要的输出。

修改后的完整代码:

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 __str__(self):
        return f"{self.quantity_on_hand} {self.name}(s) at a unit price of {self.unit_price}."

# 测试代码
item = InventoryItem(name="Banana", unit_price=5, quantity_on_hand=3)
print(item)

运行后输出:

3 Banana(s) at a unit price of 5.

如果需要严格处理单复数(比如数量为1时显示Banana而非Banana(s)),可以优化__str__方法的逻辑:

def __str__(self):
    item_label = self.name if self.quantity_on_hand == 1 else f"{self.name}(s)"
    return f"{self.quantity_on_hand} {item_label} at a unit price of {self.unit_price}."

此时当quantity_on_hand为1时,输出会变为1 Banana at a unit price of 5.,更符合日常表达习惯。

内容的提问来源于stack exchange,提问作者wueli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:57:41