zellux 的博客

Python中inner function的binding处理

BBS上的一个帖子,问题是 def a(): def b(): x += 1 x = 1 print "a: ", x b() print "b: ", x def c(): def d(): x[0] = [4] x = [3] print "c: ", x[0] d() print "d: ", x[0] 运行a()会报UnboundLocalError: local variable ‘x’ referenced before assignment 但是运行c()会正确地显示3和4。 原因在于原因在于CPython实现closure的方式和常见的functional language不同,采用了flat closures实现。 “If a name is bound anywhere within a code block, all uses of the name within the block are treated as references to the current block. 阅读全文 →