首页 > 解决方案 > 从 Python 数据类装饰器中的 __repr__ 方法中删除引号

问题描述

在定义类时在 Python 中使用dataclass装饰器时,作为字符串的字段值以该对象的字符串表示形式输出,并带有引号。请参阅以下文档中的屏幕截图dataclass(链接此处):

在此处输入图像描述

问题是,如何删除引号?换句话说,我怎样才能最好地覆盖装饰器__repr__附带的方法dataclass来进行这个简单的更改?根据上面的示例,我希望输出如下所示:

InventoryItem(name=widget, unit_price=3.0, quantity_on_hand=10)

标签: pythonpython-dataclasses

解决方案


您可能必须更换__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)

推荐阅读