2017-05-12 3 views
0

다음은 유스 케이스입니다. 클래스 인스턴스를 json 또는 python 사전 값으로 사용하는 방법

class EvaluateCustomMethod(object): 
    faker = Faker() 
    def __init__(self, custom_method, cardinality=1): 
     self.custom_method = custom_method 
     self.cardinality = cardinality 
    @property 
    def random_first_name(self): 
     return self.faker.first.name() 

    def call_method_n_times(self): 
     return [getattr(self, self.custom_method) \ 
       for _ in range(self.cardinality)] 

f = EvaluateCustomMethod('random_first_name', 1) 
f.call_method_n_times() 

는 내가 객체를 인스턴스화 한 후 메서드 호출을 내가 인스턴스를 만들 때 직접 내 목표를 달성 할 필요가 없습니다 수있는 방법을 찾기 위해 노력하고있다.

내 궁극적 인 목표는 이것이다 : 할

  {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)}} 

이것은 다음 이전 question

+0

이 질문은 다른 [1] (http://stackoverflow.com/questions/43944858/how-to-pass-method-name-as-a-parameter-in- python-class/43945029 # 43945029). 이것은 SO에 대한 일반적인 관행입니다. – Kanak

+0

당신이 ('__new__' 메소드를 오버라이드하여) 할 수있다하더라도 이것을하지 말아야합니다. EvaluateCustomMethod를 함수로 리팩토링하면됩니다. – rantanplan

답변

1

대답에 링크가하지, 무엇을 원하는 이후 제안 된 것은 리팩토링 필요성에 대한 강력한 신호 일 가능성이 매우 높습니다.

한 가지 가능한 방법은 생성자 __new__을 사용하여 클래스를 인스턴스화 할 때 반환 될 내용을 결정하는 것입니다.

class EvaluateCustomMethod(object): 

    faker = Faker() 

    def __new__(cls, custom_method, cardinality=1):   
     instance = super(EvaluateCustomMethod, cls).__new__(cls) 
     instance.custom_method = custom_method 
     instance.cardinality = cardinality 
     return instance.call_method_n_times() 

    @property 
    def random_first_name(self): 
     return self.faker.first.name() 

    def call_method_n_times(self): 
     return [getattr(self, self.custom_method) \ 
       for _ in range(self.cardinality)] 

을 다음과 같이 어느 그래서 당신이 수행 할 수 있습니다 무엇을, 더 클래식,

class EvaluateCustomMethod(object): 

    faker = Faker() 

    def __init__(self, custom_method, cardinality=1): 
     self.custom_method = custom_method 
     self.cardinality = cardinality 

    @property 
    def random_first_name(self): 
     return self.faker.first.name() 

    def call_method_n_times(self): 
     return [getattr(self, self.custom_method) \ 
       for _ in range(self.cardinality)] 

    def __call__(self): 
     return self.call_method_n_times() 
것으로, 권장하지 않습니다 그래서 같은 __new__을 무시, 실제로

>>> EvaluateCustomMethod('random_first_name', 1) 
['John'] 
>>> {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)}} 
{"test" : {"name" : ['Jack']}} 


하지만을 반환

똑같은 것을 되 돌리는 것이지만 정확히 무엇을한다고 생각하는지 정확하게 처리하는 것

>>> EvaluateCustomMethod('random_first_name', 1) 
['Jacques'] 
>>> {"test" : {"name" : EvaluateCustomMethod('random_first_name', 1)()}} 
{"test" : {"name" : ['Richard']}} 
+0

그것이 제가 찾고 있던 것입니다. 신경 쓸 수 없다면 논리를 설명하는 주석을 추가하십시오. 나는 OP와 매우 다른 새로운 도움이 될 것입니다. 빠른 응답을 감사하십시오. – June2017

+1

@ new_kid_07 비록 내가 대답을 하향식하지 않겠지 만 (당신이 원하는 대답을하기 때문에), 당신이 OP에 매우 익숙하다는 것이 명백하기 때문에 이것은 분명히 원하지 않는 일입니다. 코드를 함수로 리펙토링해야합니다. 그것이 우리가 가지고있는 이유입니다! – rantanplan

+1

@new. 나는 rantanplan에 동의한다. – Kanak