python学习~闭包
2013-05-07 15:44
302 查看
闭包:在函数内部定义函数,即(外部)函数体内存在内部函数,且在内部函数里对外部函数作用域(非全局作用域)的变量进行
引用操作。那么内部函数称之为闭包
闭包作用1:实现函数的静态变量(隐藏、记忆内部状态)
闭包作用2:实现装饰器
运行结果:
junmin调用hello第0次
hello
junmin调用hello第1次
world
引用操作。那么内部函数称之为闭包
闭包作用1:实现函数的静态变量(隐藏、记忆内部状态)
# coding=utf-8 def counter(start_at=0): count=[start_at] def incr(): count[0]=count[0]+1 return count[0] return incr count=counter() print count() #1 print count() #2
闭包作用2:实现装饰器
def deco_para(w): def deco_fun(func): counter=[0] def deco(*args,**kargs): print u'%s调用%s第%s次' %(w,func.__name__ ,counter[0]) counter[0]+=1 return func(*args,**kargs) return deco return deco_fun @deco_para('junmin') def hello(s): print s hello('hello') hello('world')
运行结果:
junmin调用hello第0次
hello
junmin调用hello第1次
world
相关文章推荐
- python学习笔记 --- 关于python的闭包
- python基础学习-闭包
- 深入学习python(三) 闭包(Decorator)与装饰器(Closure)
- Python学习笔记之函数作为返回值、闭包的解释
- python闭包学习笔记三
- 【学习笔记】用python的非闭包、闭包(函数式编程)、面向对象方法解决旅行者问题
- Python学习笔记——闭包,装饰器
- Python学习笔记——利用闭包写递增函数
- python 学习(十九)之浅谈闭包
- Python学习之闭包
- python闭包学习笔记四
- Python学习笔记之函数作为返回值、闭包的解释
- Python学习8--嵌入函数与闭包
- python学习返回函数(闭包)
- Python语言学习笔记之闭包
- python学习笔记--闭包
- python基础学习-闭包
- python闭包学习
- 学习笔记-小甲鱼Python3学习第二十讲:函数:内嵌函数和闭包
- Python教程学习简记9--Python 返回函数 闭包