从 Python 数据类装饰器中的 __repr__ 方法中删除引号
Remove quotes from __repr__ method in Python dataclass decorator
在定义 class 时在 Python 中使用 dataclass
装饰器时,作为字符串的字段值将在该对象的字符串表示形式中用引号输出。请参阅下面来自 dataclass
文档 (link here) 的屏幕截图:
问题是,如何删除引号?换句话说,我怎样才能最好地覆盖 dataclass
装饰器附带的 __repr__
方法来进行这个简单的更改?按照上面的示例,我希望输出如下所示:
InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)
您可能必须替换 __repr__
实现。例如:
from dataclasses import dataclass, _FIELD, _recursive_repr
@dataclass
class InventoryItem:
name: str
unit_price: float
quantity_on_hand: int
@_recursive_repr
def __repr__(self):
# only get fields that actually exist and want to be shown in a repr
fields = [k for k, v in self.__dataclass_fields__.items() if v._field_type is _FIELD and v.repr]
return (
self.__class__.__qualname__
+ "("
# fetch fields by name, and return their repr - except if they are strings
+ ", ".join(f"{k}={getattr(self, k)}" if issubclass(type(k), str) else f"{k}={getattr(self, k)!r}" for k in fields)
+ ")"
)
item = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)
print(item)
结果:
InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)
在定义 class 时在 Python 中使用 dataclass
装饰器时,作为字符串的字段值将在该对象的字符串表示形式中用引号输出。请参阅下面来自 dataclass
文档 (link here) 的屏幕截图:
问题是,如何删除引号?换句话说,我怎样才能最好地覆盖 dataclass
装饰器附带的 __repr__
方法来进行这个简单的更改?按照上面的示例,我希望输出如下所示:
InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)
您可能必须替换 __repr__
实现。例如:
from dataclasses import dataclass, _FIELD, _recursive_repr
@dataclass
class InventoryItem:
name: str
unit_price: float
quantity_on_hand: int
@_recursive_repr
def __repr__(self):
# only get fields that actually exist and want to be shown in a repr
fields = [k for k, v in self.__dataclass_fields__.items() if v._field_type is _FIELD and v.repr]
return (
self.__class__.__qualname__
+ "("
# fetch fields by name, and return their repr - except if they are strings
+ ", ".join(f"{k}={getattr(self, k)}" if issubclass(type(k), str) else f"{k}={getattr(self, k)!r}" for k in fields)
+ ")"
)
item = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)
print(item)
结果:
InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)