python--closure

closure概念:在一个内部函数中,对外部作用域的变量进行引用,那么内部函数就被认为是closure(闭包)

自由变量:定义在外部函数内,被内部函数引用或者使用的变量为自由变量

函数func_closure 在函数被调用前和调用后使用,效果是一样的

#!/user/bin/env python
#coding:UTF-8
#func_closure: 这个属性仅当函数是一个闭包时有效
#指向一个保存了所引用到的外部函数的变量cell的元组
#如果该函数不是一个内部函数,则始终为None。这个属性也是只读的。
output = '<int %r id = %#0x val =%d>'
w = x = y = z = 1

def f1():
    print 'f1() start'
    x = y = z = 3

    def f2():
        print 'f2() start'
        y = z = 3
        
        def f3():
            print 'f3() start'
            z = 4
            print output%('w',id(w),w)
            print output%('x',id(x),x)
            print output%('y',id(y),y)
            print output%('z',id(z),z)
            'f3() end'
        print 'f3.func_closure'
        clo = f3.func_closure
        if clo:
            print "f3 closure vars:",[str(c) for c in clo]
        else:
            print 'no f3 closure vars'
            print 'f2() call f3()'
        print 'in f2 call f3'
        f3()
        print 'f2() end'
    print 'f1.func_closure'
    clo = f2.func_closure
    if clo:
        print "f2 closure vars:",[str(c) for c in clo]
    else:
        print "no f2 closure vars"
    print 'in f1() call f2()'
    f2()
    print 'f1() end'
print 'f1.func_closure'
clo = f1.func_closure
if clo:
    print "f1 closure vars:",[str(c) for c in clo]
else:
    print "no f1 closure vars"
print 'call f1()'
f1() 

 

转载于:https://www.cnblogs.com/Pierre-de-Ronsard/archive/2012/08/20/2647812.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值