2017-05-12 8 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

答えにリンクされているが、ありません何をやりたいと思っ以来リファクタリングの必要性の強いシグナルとなる可能性が非常に高いです。

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

関連する問題