python - 从 Python 数据类装饰器中的 __repr__ 方法中删除引号
问题描述
在定义类时在 Python 中使用dataclass
装饰器时,作为字符串的字段值以该对象的字符串表示形式输出,并带有引号。请参阅以下文档中的屏幕截图dataclass
(链接此处):
问题是,如何删除引号?换句话说,我怎样才能最好地覆盖装饰器__repr__
附带的方法dataclass
来进行这个简单的更改?根据上面的示例,我希望输出如下所示:
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)
推荐阅读
- python - 有没有办法在元素前面添加数字
- python - 内存不足 - Keras tensorflow GPU - 梯度累积
- java - 如何在 Google Ads API 中查询最近停用的广告系列
- java - @PreAuthorize 带有允许角色列表的注释包装器
- vba - vbCFBitmap 变量未定义
- android-studio - Android Studio 的播放按钮未启用
- javascript - 仅自动滚动子组件,而不是父组件
- r - R中的字符串替换不正确
- ios - 使用 IOS 13 在 Xamarin.iOS 上向右滑动不会动画效果
- c# - Entity Framework Core 3 - 具有来自存储过程的一些字段的模型