python闭包示例
def average(*arg):
print ('in average')
return sum(arg)/len(arg)
def proc(func):
def verify(*arg):
print ('in proc.verify')
if len(arg) == 0:
return 0
for val in arg:
if not isinstance(val, int):
return 0
return func(*arg)
return verify
test_avg = proc(average)
print test_avg(1,2,3,4,5)
执行结果:
in proc.verify
in average
3
装饰器示例
def proc(func):
print 'call proc'
def verify(*arg):
print ('in proc.verify')
if len(arg) == 0:
return 0
for val in arg:
if not isinstance(val, int):
return 0
return func(*arg)
return verify
@proc
def average(*arg):
print ('in average')
return sum(arg)/len(arg)
print average(1,2,3,4,5)
执行结果:
call proc
in proc.verify
in average
3
如上所示,实质上,装饰器是闭包的一种应用。
扩展阅读
何为闭包
在Python中,所谓的闭包是一个包含有环境变量取值的函数对象。
比较欣赏这句话:闭包不过是对某种程序结构起的一个名字,定义是次要的,知道怎么用才是重要的。
Wikipedia
a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.