나는 상용구 코드없이 간단한 클래스를 정의하기 위해 attrs을 사용하고 있습니다. 데코레이터는 모든 속성의 값을 보여주는 __repr__
을 자동으로 생성합니다. 기본 값이없는 애트리뷰트 만 표시하고 싶습니다.attr.s의 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)
이 작업을 수행하는 데 비교적 쉬운 방법이 있습니까? 이것은 다음과 같은 올바른 행동 결과
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
:
응답 해 주셔서 감사합니다. 'repr'에 대한 더 많은 커스터마이징은 확실히 훌륭 할 것입니다. 당분간 맞춤형 데코레이터가 내 특별한 필요를 충족시킵니다. –