gpt4 book ai didi

python - 从 Python 数据类装饰器中的 __repr__ 方法中删除引号

转载 作者:行者123 更新时间:2023-12-04 07:40:31 24 4
gpt4 key购买 nike

使用 dataclass 时Python 中的装饰器在定义类时,作为字符串的字段值以该对象的字符串表示形式输出,并带有引号。请参阅以下来自 dataclass 的截图文档(链接 here):
enter image description here
问题是,如何删除引号?换句话说,我怎样才能最好地覆盖 __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 数据类装饰器中的 __repr__ 方法中删除引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67505861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com