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

huangapple go评论70阅读模式
英文:

How can I overwrite the default print output of a python dataclass?

问题

给定dataclasses文档中的InventoryItem示例。

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """用于跟踪库存中物品的类。"""
    name: str
    unit_price: float
    quantity_on_hand: int = 0

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

# 输出:
# InventoryItem(name='Banana', unit_price=5, quantity_on_hand=3)

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

"3个香蕉,单价为5。"
英文:

Given the InventoryItemexample from the dataclasses documentation.

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)

How to overwrite the standard output message such that the output string

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

is displayed?

答案1

得分: 5

首先,dataclasses是普通的类,没有所谓的dataclass类型。

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

  • 定义__repr__方法

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

    ...对象的“官方”字符串表示。如果可能的话,它应该看起来像一个有效的Python表达式,可以用来重新创建具有相同值的对象。

    你想要的表示形式不是一个可以重新创建对象的有效表达式,所以这不是一个好选择。

  • 定义__str__方法

    再次参考数据模型

    由str(object)、内置函数format()和print()调用,用于计算对象的“非正式”或可打印的字符串表示。[...]这个方法与object.__repr__()的区别在于,不要求__str__()返回一个有效的Python表达式。

    这是我推荐使用的方法。

from dataclasses import dataclass

@dataclass
class InventoryItem:
    """用于跟踪库存中物品的类。"""
    name: str
    unit_price: float
    quantity_on_hand: int = 0
    
    def __str__(self):
        return f"{self.quantity_on_hand} {self.name}(s) 单价为 {self.unit_price}"
>>> item = InventoryItem(name="香蕉", unit_price=5, quantity_on_hand=3)
>>> item  # 调用__repr__方法
InventoryItem(name='香蕉', unit_price=5, quantity_on_hand=3)
>>> print(item)  # 调用__str__方法
3 个香蕉 单价为 5
英文:

First of all, dataclasses are normal classes. There is no such a thing as a dataclass type.

There are two ways to override the standard output message of any Python class:

  • define the __repr__ method

    In Python's data model this method is...
    > ... the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value.

    The representation that you want is not a valid expression to recreate the object, so this is not a good choice.

  • define the __str__ method

    Again from the data model:
    > Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. [...] This method differs from object.__repr__() in that there is no expectation that __str__() return a valid Python expression.

    This is what I would recommend using.

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)
>>> item  # __repr__ being called
InventoryItem(name='Banana', unit_price=5, quantity_on_hand=3)
>>> print(item)  # __str__ being called
3 Banana(s) at a unit price of 5

huangapple
  • 本文由 发表于 2023年7月27日 16:22:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定