英文:
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 InventoryItem
example 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__
methodIn 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__
methodAgain 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论