2017-02-15 1 views
0

어떻게 아래의 클래스가 사용하는 변환 할 수 attrs library :파이썬 attrs에 라이브러리 및 참조 예 방법

class MyClass(object): 
    def __init__(self, api, template=None, **kwargs): 
     self.api = api 
     self.param1 = param1 
     if template is not None: 
      self.template = api.get_template(desc=template) 

구체적으로 어떻게 다른 사람의 초기화에 하나 개의 매개 변수의 의존성을 처리합니까? 내 최초의 시도로,이 같은 클래스로 시작 :

@attr.s 
class MyAttrClass(object): 
    api = attr.ib() 
    param1 = attr.ib() 

하지만 난 template 속성을 처리하는 방법이 확실하지? 내 초기 생각은 다음과 같습니다.

def __attrs_post_init__(self): 
    self.template = api.get_template(desc=template) 

그래도이 작업을 수행하는 더 좋은 방법이 있는지 궁금합니다.

답변

0

귀하의 질문에 'param1'을 따르기가 어렵고 'kwargs'에서 오는 것이라고 가정 할 수 있습니까?

@attr.s 
class MyAttrClass(object): 
    api = attr.ib() 
    template = attr.ib(default=None) 
    param1 = attr.ib() 

    def __attrs_post_init__(self): 
     if self.template is not None: 
      self.template = api.get_template(desc=template) 

템플릿 속성을 처리 할 수있는 실행 가능한 해결책이 될,하지만 난 아직이다 해결하는 것은 kwargs로 처리하는 방법입니다해야한다. 나는 그 자체를 조사하고 있으므로 일단 발견하면 해결책을 게시 할 것이다.

1

나는 takes_self argument to Factory이 당신에게 유용 할 것이라고 생각합니다. 내가 여기에서 볼 생각

하나의 문제는 당신이 self.template로 설정하는 것보다 것은 다른 종류의 (아마도 str) (아마도 Template가)처럼 당신이 외모와 템플릿이라는 주장을 복용하는 것입니다. 다른 이름을 지정하고 다음과 같이하십시오 :

from attr import Factory, attrib, attrs 
from attr.validators import instance_of 

from my.code import API, Template 

@attrs 
class Foo(object): 
    api = attrib(validator=instance_of(API)) 

    _template_name = attrib(validator=instance_of(str)) 

    template = attrib(
     validator=instance_of(Template), 
     default=Factory(
      lambda self: self.api.get_template(self._template_name) 
     ), 
     takes_self=True, 
     init=False, 
    )