一、定义一个Python Closure 函数
首先直接上菜,然后再聊
例一:define a closure function
def print_msg(msg):
# This is the outer enclossing function
def printer():
# This is the nested function
print(msg)
return printer
# call this function
another = print_msg('hello')
another()
输出结果:
hello
上面的 print_msg() 函数被调用,传入的参数为“hello”,这个返回的函数指向another。 在调用another() 函数时,信息仍会被记住,尽管已经执行完print_msg() 函数。这就是 closure。
##例二: del
del print_msg
another()
print_msg('hello')
输出为:
hello
Traceback (most recent call last):
File “G:/Project/Learn_python3/Demo05/blog.py”, line 15, in
print_msg(‘hello’)
NameError: name ‘print_msg’ is not defined
这就说明,在enclosing function的值被记住了,当删除函数后,调用another()仍会有输出。
二:使用closure的条件?
- 我们必须得有内层函数;
- 内层函数需要调用外层函数的参数;
- 在外层函数需要返回内层函数
三、什么时候用 closure?
closure 有什么好处?
- 可以避免使用全局变量
- 提供数据隐藏的形式
例二: make_multipier_of()
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
times3 = make_multiplier_of(3)
times5 = make_multiplier_of(5)
print(times3(3))
print(times3(times5(2)))
运行结果:
9
30