JavaScript 猿でもわかるクロージャ超入門というページを見てクロージャの基本を学んでいるのですが、コードをPythonに書き換えいじっていると挙動に納得できないところがあります。
呼び出すたびに、0,1,2,...を返すような関数を定義するというものなのですが、Code1だと動きます。f = outer()
という部分を削るとどうなるかを試したものがCode2で、この場合0しか返されません。outer()
の返り値をreturn inner
ではなくreturn inner()
に変えたものがCode3です。この場合、1度目は0が返されるのですが、2度目でTypeError
になります。
自分の試行錯誤の中で生まれたのがCode2,3で最終的にCode1に行き着いたのですが、どうして2や3が上手く動かないのかが納得できていません。
難しい話でも構わないので、どこがどうして悪いのかをどなたか解説していただけないでしょうか?
Python
1# Code1 正しく動くもの 2def outer(): 3 x = 0 4 def inner(): 5 nonlocal x 6 print(x) 7 x += 1 8 return inner 9f = outer() 10for i in range(3): 11 f() 12> 0 13> 1 14> 2
Python
1# Code2 2def outer(): 3 x = 0 4 def inner(): 5 nonlocal x 6 print(x) 7 x += 1 8 return inner 9# f = outer()を削除 10for i in range(3): 11 outer()() # f()の代わり 12> 0 13> 0 14> 0
Python
1# Code3 2def outer(): 3 x = 0 4 def inner(): 5 nonlocal x 6 print(x) 7 x += 1 8 return inner() # innerではなくinner() 9f = outer() 10for i in range(3): 11 f() 12> 0 13> TypeError: 'NoneType' object is not callable
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。