python学习~闭包

来源:互联网 发布:淘宝代付超限怎么办 编辑:程序博客网 时间:2024/05/16 06:21

闭包:在函数内部定义函数,即(外部)函数体内存在内部函数,且在内部函数里对外部函数作用域(非全局作用域)的变量进行

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


闭包作用1:实现函数的静态变量(隐藏、记忆内部状态)


# coding=utf-8def counter(start_at=0):    count=[start_at]    def incr():        count[0]=count[0]+1        return count[0]    return incrcount=counter()print  count()  #1print  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


原创粉丝点击