One: the basic premise
Closure function with a scope namespace = + + nested function object function
The core point: the name of the relationship is to find the function definition stage prevail
Two: What is the closure function
"Closed" function refers to the function is built-in functions
"Package" function refers to the function of the outer layer contains a reference to the name of the function scope (not on the global scope)
Closure function: namespace application and scope of the nested function +
def f1():
x = 33333333333333333333
def f2():
print(x)
f2()
x=11111
def bar():
x=444444
f1()
def foo():
x=2222
bar()
foo()
输出:33333333333333333333
思路:调用的是函数foo(),函数foo()内的x=2222未被调用,调用了函数bar()
函数bar()内的x=444444未被调用,调用了函数f1()
函数f1()内定义了x,定义了函数f2(),函数f2()内输出x
函数f2()内未定义x,就去f1()中,找到了x=33333333333333333333
最后函数f1()调用了函数f2(),输出33333333333333333333
def f1():
x = 33333333333333333333
def f2():
print('函数f2:',x)
return f2
f=f1() # 调用f1(),返回函数f2(),输出:函数f2:33333333333333333333
def foo():
x=5555
f()
foo() # 调用foo(),foo()内调用了f(),也就是调用了f2,输出:函数f2:33333333333333333333
输出:函数f2: 33333333333333333333
Three: Why have closure function == "Closures function
Two kinds of transmission parameters as a function of the body by:
Way: the parameter defines the function body directly molded required parameters
def f2(x):
print(x)
f2(1)
f2(2)
f2(3)
输出:
1
2
3
Second way: use the closure function
def f1(x): # x=3
# x=3
def f2():
print(x)
return f2
x=f1(3)
print(x)
x()
输出:
<function f1.<locals>.f2 at 0x02F734A8>
3