写下这篇博客,起源于Tornado邮件群组的这个问题how to use outer variable in inner method,这里面老外的回答很有参考价值,关键点基本都说到了。我在这里用一些有趣的例子来做些解析,简要的阐述下Python的闭包规则,首先看一个经典的例子:
def foo():
a = 1
def bar():
a = a + 1
# print a + 1
# b = a + 1
# a = 1
print id(a)
bar()
prin
闭包函数初探
通常我们定义函数都是这样定义的
def foo():
pass
其实在函数式编程中,函数里面还可以嵌套函数,如下面这样
def foo():
print(hello world in foo)
def bar():
print(hello world in bar)
此时我们调用foo函数,执行结果会是什么样子的呢??
hello world in foo
结果如上所示,只会执行foo函数的第一层函数,bar函数是不会被执行的。为什么呢
实际上来说,不管函数写在哪个部