如何重写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
相关产品推荐
相关产品推荐

