您的位置:首页 > 编程语言 > Python开发

python学习~闭包

2013-05-07 15:44 302 查看
闭包:在函数内部定义函数,即(外部)函数体内存在内部函数,且在内部函数里对外部函数作用域(非全局作用域)的变量进行

引用操作。那么内部函数称之为闭包

闭包作用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: