0

定型コードなしで単純なクラスを定義するためにattrsを使用しています。デコレーター__repr__は、すべての属性の値を示す を自動的に生成します。デフォルト値を持たない属性のみを表示したい:

>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)

これを達成する合理的に簡単な方法はありますか?

4

3 に答える 3

0

次のクラスデコレータを使用して、方法を見つけたと思います。

def no_default_vals_in_repr(cls):
    """Class decorator on top of attr.s that omits attributes from srepr that
    have their default value"""

    defaults = OrderedDict()
    for attribute in cls.__attrs_attrs__:
        defaults[attribute.name] = attribute.default

    def repr_(self):
        real_cls = self.__class__
        qualname = getattr(real_cls, "__qualname__", None)
        if qualname is not None:
            class_name = qualname.rsplit(">.", 1)[-1]
        else:
            class_name = real_cls.__name__
        attributes = defaults.keys()
        return "{0}({1})".format(
            class_name,
            ", ".join(
                name + "=" + repr(getattr(self, name))
                for name in attributes
                if getattr(self, name) != defaults[name]))

    cls.__repr__ = repr_
    return cls

これにより、次の正しい動作が発生します。

>>> @no_default_vals_in_repr
... @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()
Coordinates()
>>> Coordinates(x=0, y=0)
Coordinates()
>>> Coordinates(x=1)
Coordinates(x=1)
>>> Coordinates(x=1, y=1)
Coordinates(x=1, y=1)
于 2017-12-05T21:40:23.030 に答える
0

__repr__そのシナリオでは、必ず独自のものを提供する必要があります。クラス デコレータを設定することを忘れないでくださいrepr=False(将来的に不要になることを願っています。 https://github.com/python-attrs/attrs/issues/324を参照してください)。

于 2018-02-08T21:34:26.517 に答える