Python 闭包简介

闭包

  1. 闭包的模板
	# 闭包的定义
def outer(): # 外层函数
    init=0# 外层变量
    def inner(): # 内层函数
        return init+1 # 内层调用
    return inner # 外层返回
# 闭包的使用
get_inner=outer()
print(get_inner())

1

  1. 闭包的基本结构
    • 外层函数
    • 内层函数
    • 外层函数非全局变量
    • 内层函数使用外层变量
    • 外层函数返回内层函数指针
  2. 对闭包的理解
    • 闭包本质上是一种函数的写法
    • outer() 内的变量不能直接被外界直接访问
    • 外层函数执行结束后,由于内层函数仍要用到外层变量,故外层函数的变量的内存不会被释放
    • 内层函数使用的是外层函数的变量,故不受外界干扰(本质是 python 变量的覆盖规则)
    • 注意,由于外层变量不被释放,闭包的内存占用大
  3. 在闭包中修改外层变量
# 闭包的定义
def outer(): # 外层函数
    init=0# 外层变量
    def inner(): # 内层函数
        nonlocal init # 使用 nonlocal 声明变量
        init=1 # 修改 init
        return init+1 # 内层调用
    return inner # 外层返回
# 闭包的使用
get_inner=outer()
print(get_inner())

2

  1. 在外界中初始外层变量
# 闭包的定义
def outer(n): # 外层函数
    init=n# 外层变量
    def inner(): # 内层函数
        return init+1 # 内层调用
    return inner # 外层返回
# 闭包的使用
get_inner=outer(3)
print(get_inner())

4

  1. 闭包的作用
    • 闭包可以把保护变量,防止变量被意外修改
# 如果使用全局变量
sum = 0
def add_1():
    print(sum+1)
sum=2
add_1() # sum 轻易被外界修改

3

# 如果使用闭包
def outer():
    sum=0
    def add_1():
        print(sum+1)
    return add_1
sum=2
fun=outer()
fun() # sum 不被外界修改

15
23

  1. 判断函数中存在闭包结构
    • __cloure__ 属性
# 有闭包时,__closure__ 非 None
def linecreate(k,b):
    def linecount(x):
        return k*x+b
    return linecount
line=linecreate(1,1)
print(line.__closure__)

(<cell at 0x756e590f79d0: int object at 0x627f6c9de348>, <cell at 0x756e590f7400: int object at 0x627f6c9de348>)

# 1. 无闭包时,__closure__ None
def linecreate(k,b):
    def linecount(x):
        return x
    return linecount
line=linecreate(1,1)
print(line.__closure__) # line 本质是 linecount

None

# 2. 无闭包时,line.__closure__不存在
def linecreate(k,b):
    def linecount(x):
        return x
line=linecreate(1,1)
print(line.__closure__) # line 本质是 linecount

AttributeError Traceback (most recent call last)
Cell In[46], line 6
4 return x
5 line=linecreate(1,1)
----> 6 print(line.closure) # line 本质是 linecount

AttributeError: ‘NoneType’ object has no attribute ‘closure

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值