1、闭包的定义
闭包常与函数嵌套、变量作用域等联系在一起。非专业地来说,闭包的表现形式是:一个外部函数里嵌套了一个内部函数,在主函数中调用外部函数时,外部函数会返回内部函数并赋值于一个变量,该变量记录外部函数的属性值,并允许该变量访问。一些公共的、已知的初始化、变量可以放到外部函数作用域,这样能避免代码的重复。
一个闭包示例如下所示(python2,如无特殊说明,以下代码均为python2):
# 实现累积计数功能
# 为何 now 为常量时不行呢,如 now = 0
def outer_function():
now = [0]
def inner_count():
now[0] = now[0] + 1
print now[0]
return inner_count
count = outer_function()
count()
count()
count()
2、函数内部修改全局变量的方法
MIX = 1
def f():
MIX += 1 #会报错:UnboundLocalError: local variable 'MIX' referenced before assignment
f()
MIX = 1
def f():
global MIX # 这会告诉编译器在该函数的使用的变量MIX已经在全局中声明了,使用那个全局变量就行
MIX += 1
print MIX # 打印2
f()
3、函数嵌套的作用
函数嵌套有两大作用
(1)减少代码冗余
# -*- coding:UTF-8 -*-
# 假设用递归实现累加运算,为了程序的鲁棒,在进行累加前需要检查输入是否正确
# 不使用函数嵌套,每一次递归都会重新判断一下异常
def accumulate(input):
if not isinstance(input, int):
raise Exception('Input must be integer')
if input < 0:
raise Exception('Input must be larger than zero')
if input == 1:
return 1
return input + accumulate(input-1)
# 使用函数嵌套,只需判断一次异常
def accumulate_nest(input):
if not isinstance(input, int):
raise Exception('Input must be integer')
if input < 0:
raise Exception('Input must be larger than zero')
def inner(input):
if input == 1:
return 1
return input + inner(input-1)
return inner(input)
print accumulate_nest(3)
(2)提高代码安全性
内部函数接口只会暴露给其嵌套的外部函数,其它地方是无法访问内部函数的,这样就可以在内部函数中处理一些私密的信息。