2017-07-16 8 views
0

私はPython3を使用しています。「Python for Data Analysis」を読んで、クロージャを使用する次のコードを実行してみてください。Python3でクローズ結果を得る方法

def make_closure(a): 
    def closure(): 
     print('I know the secret: %d' % a) 
    return make_closure 

make_closure(5) 

本があることを私に言っている間、結果は

Out[70]: <function __main__.make_closure> 

ある「上記の場合には、返されたクロージャは いつも私が秘密を知って印刷されますので:5あなたはそれを呼び出すたび」

結果をブックとして取得するにはどうすればよいですか?それは私がPython 3を使うからですか?

+1

'make_closure'ではなく' closure'を返す必要があります。 –

+0

また、返された関数を呼び出す必要があります。 – AChampion

+0

@Renkeいいです、害はありません:-) –

答えて

1

あなたはむしろmake_closureよりclosureを返却する必要があります。 closure閉鎖あり、そしてmake_closureはクロージャを作成する機能である:

>>> def make_closure(a): 
...  def closure(): 
...   print('I know the secret: %d' % a) 
...  return closure 
... 
>>> f = make_closure(5) 
>>> f() 
I know the secret: 5 

あなたは冒険を感じている場合は、あなたがf用クロージャの内側にあるものを見るために__closure__属性を使用することができます。

>>> f.__closure__[0].cell_contents 
5 
>>> 
1

閉鎖は、内側の関数を返す必要があり、それは例えば、呼ばれる必要がある。:

>>> def make_closure(a): 
...  def closure(): 
...   print('I know the secret: %d' % a) 
...  return closure 
... 
>>> secret5 = make_closure(5) 
>>> secret2 = make_closure(2) 
>>> secret5() 
'I know the secret: 5' 
>>> secret5() 
'I know the secret: 5' 
>>> secret2() 
'I know the secret: 2' 
関連する問題