2017-12-05 1 views
0

나는 상용구 코드없이 간단한 클래스를 정의하기 위해 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 

:

답변

0

아니, 거기되지 않고 또한 상당히 구체적이다 의뢰. :) 사람들은 더 많은 방법을 묻습니다. repr의 출력은 예를 들어. 일단 유포되면 유스 케이스를 더 쉽게 만들 수 있습니다. 그러나 저는 지금 당장에 적극적으로 노력하는 사람은 알지 못합니다.

+0

응답 해 주셔서 감사합니다. 'repr'에 대한 더 많은 커스터마이징은 확실히 훌륭 할 것입니다. 당분간 맞춤형 데코레이터가 내 특별한 필요를 충족시킵니다. –

0

가 생각 나는 다음 클래스 장식과 함께하는 방법을 알아 냈

>>> @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) 
0

해당 시나리오의 경우 자신의 __repr__을 제공해야합니다. 클래스 데코레이터에 repr=False을 설정하는 것을 잊지 마십시오 (나중에 불필요한 내용이 있으니 https://github.com/python-attrs/attrs/issues/324 참조).