python 闭包

闭包(以一个函数里面还有一个函数说明)

只用在第二个函数引用了包含着它的第一个函数定义的变量时,这才叫做闭包

---------------------------------------------------------------------------------------------------------------------------------

以函数返回

def curve_pre():
    def curve():
        print("This is a function")
    return curve
f = curve_pre()
f()
输出:This is a function

---------------------------------------------------------------------------------------------------------------------------------


闭包 = 函数 + 函数变量(函数定义时候)
def curve_pre():
    a = 25
    def curve(x):
        return a*x*x
    return curve
a = 10
f = curve_pre()
print(f(2))
输出:100

---------------------------------------------------------------------------------------------------------------------------------

没有形成闭包情况

a = 25
def curve_pre():
    def curve(x):
        return a*x*x
    return curve
a = 10
f = curve_pre()
print(f(2))
输出:40

---------------------------------------------------------------------------------------------------------------------------------

闭包说明

def curve_pre():
    b = 1
    a = 25
    def curve(x):
        return a*x*x+b
    return curve
a = 10
f = curve_pre()
print(f.__closure__)
print(f.__closure__[0].cell_contents)
print(f.__closure__[1].cell_contents)
print(f(2))
输出
(<cell at 0x0317F8B0: int object at 0x6146D5B0>, <cell at 0x0317F8D0: int object at 0x6146D430>)
25
1

101

说明只有在curve函数里用的上一层函数的参数(即时curve_pre()里面)

---------------------------------------------------------------------------------------------------------------------------------

非闭包(局部变量)

def f1():
    a = 10
    def f2():
        a = 20 
        print(a)
    print(a)
    f2()
    print(a)
f1()
输出:

10

20

10

---------------------------------------------------------------------------------------------------------------------------------

旅行者 从一开始出去

先走2步,共2步;再走3步,共5步;最后走6步,共11步

#全局变量
# origin = 0
# def go(step):
#     global origin
#     new_pos = origin + step
#     origin = new_pos
#     return origin
#
# print(go(2))
# print(go(3))
# print(go(6))

 
#闭包   #并没有改变origin的值,origin一直都是0
origin = 0
def factory(pos):
    def go(step):
        nonlocal pos  #不是局部变量
        new_pos = pos + step
        pos = new_pos
        return pos
    return go
turist = factory(origin)
print(turist(2))
print(turist(3))
print(turist(6))
#并没有改变origin的值,origin一直都是0



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值