Python - 闭包

1.函数引用

def Test():
    print("---Test Fun---")

python中函数名和C、C++等语言中的函数指针类似,Python函数名称为函数代码块的指针。

2.闭包

#定义一个函数
def TestFun(number):
    #在函数内部在定义一个函数,并且这个函数用到了外边函数的变量
    number_in = number + 100;
    print(number_in)
    def Test_in(number_in):
        print("Test_in=>%d"%number_in)
        return number + number_in
    return Test_in

ret = TestFun(100)
print(ret(20))
print(ret(30))

out:
200
Test_in=>20
120
Test_in=>30
130
def counter(start=0):
    count = [start]
    print(count)
    def incr():
        print(count[0])
        count[0]+=1
        return count[0]
    return incr


c1 = counter(5)
print(c1())
print(c1())

out:
[5]
5
6
6
7
#nonlocal访问外部函数的局部变量
def counter(start=0):
    def incr():
        nonlocal start
        start += 1
        return start
    return incr

c1 = counter(5)
print(c1())
print(c1())

c2 = counter(50)
print(c2())
print(c2())

print(c1())
print(c1())

print(c2())
print(c2())

out:
6
7
51
52
8
9
53
54
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值