2016-09-13 7 views
0

は、プロトタイプ/作成機能で使用するための関数内で関数の参照を取得します。 Exampleで使用されている作成機能を覚えておきたいと思います。私はそれを次のようにしました:私は2つのネストされた関数を持っている

class Example: 

    def __init__(self, str, proto): 
     self.str = str 
     self.proto = proto 

def make_prototype(proto_name): 
    class make_example: 
     def __call__(self, example_name): 
      return Example(proto_name + ' ' + example_name, self) 
    return make_example() 

proto = make_prototype('Prototype 1') 
ex1 = proto('Example 1') 
ex2 = ex1.proto('Example 2') 

私はそれが比較的エレガントで理解できる解決策だと思います。しかし、ネストされたclass make_exampleなしでそれを行う方法がありますか?最初のバージョンのようにそれを行い、関数への参照を得る方法がありますかmake_examplemake_exampleに直接入りますか?次のようなものがあります。

class Example: 
    def __init__(self, str, proto): 
     self.str = str 
     self.proto = proto 

def make_prototype(proto_name): 
    def make_example(example_name): 
     return Example(proto_name + ' ' + example_name, REFERENCE TO THIS FUNC) 
    return make_example 

proto = make_prototype('Prototype 1') 
ex1 = proto('Example 1') 
ex2 = ex1.proto('Example 2') 
+0

'return example(proto_name + '' + example_name、make_example)'? – dnit13

+0

@ dnit13:作品!最初に私は尋ねる前に一番簡単なことを試みなかった。 Pythonは驚くほどスムーズです:-)ありがとうございます。 – Michael

答えて

1

__call__クラスメソッドを使用できます。あなたの例は次のようになります:

class Example: 
    def __init__(self, str, proto): 
     self.str = str 
     self.proto = proto 

class MakePrototype(): 
    def __init__(self, name): 
     self.name = name 

    def __call__(self, proto_name): 
     return Example(proto_name, self) 



proto = MakePrototype('Prototype 1') 
ex1 = proto('Example 1') 
ex2 = ex1.proto('Example 2') 
+0

私はすでにやったことに本質的な違いはないと思っていますが、特に質問には答えません。 – Michael

+0

Uにはネストされた関数やクラスがありません。加えて、それはより平らに見える、入れ子関数は、常に私を混乱させるが、それは主観的な感情です:) – goldcoin

関連する問題