如何覆盖 python 数据类的默认打印输出?

wue*_*eli 0 python python-dataclasses

给出文档InventoryItem中的示例dataclasses

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

InventoryItem(name="Banana", unit_price=5, quantity_on_hand=3)

# OUTPUT:
# InventoryItem(name='Banana', unit_price=5, quantity_on_hand=3)
Run Code Online (Sandbox Code Playgroud)

如何覆盖标准输出消息,以便输出字符串

"3 Banana(s) at a unit price of 5."
Run Code Online (Sandbox Code Playgroud)

被展示?

edd*_*313 5

首先,数据类是普通类。不存在数据类类型这样的东西。

\n

有两种方法可以覆盖任何 Python 类的标准输出消息:

\n
    \n
  • 定义__repr__方法

    \n

    Python的数据模型中,这个方法是......

    \n
    \n

    ...对象的 \xe2\x80\x9cofficial\xe2\x80\x9d 字符串表示形式。如果可能的话,这应该看起来像一个有效的 Python 表达式,可用于重新创建具有相同值的对象。

    \n
    \n

    您想要的表示形式不是重新创建对象的有效表达式,因此这不是一个好的选择。

    \n
  • \n
  • 定义__str__方法

    \n

    再次从数据模型来看:

    \n
    \n

    由 str(object) 以及内置函数 format() 和 print() 调用,以计算对象的 \xe2\x80\x9cinformal\xe2\x80\x9d 或可良好打印的字符串表示形式。[...] 此方法与 object.__repr__() 不同,因为不期望 __str__() 返回有效的 Python 表达式。

    \n
    \n

    这是我推荐使用的。

    \n
  • \n
\n
from dataclasses import dataclass\n\n@dataclass\nclass InventoryItem:\n    """Class for keeping track of an item in inventory."""\n    name: str\n    unit_price: float\n    quantity_on_hand: int = 0\n    \n    def __str__(self):\n        return f"{self.quantity_on_hand} {self.name}(s) at a unit price of {self.unit_price}"\n
Run Code Online (Sandbox Code Playgroud)\n
>>> item = InventoryItem(name="Banana", unit_price=5, quantity_on_hand=3)\n>>> item  # __repr__ being called\nInventoryItem(name=\'Banana\', unit_price=5, quantity_on_hand=3)\n>>> print(item)  # __str__ being called\n3 Banana(s) at a unit price of 5\n
Run Code Online (Sandbox Code Playgroud)\n