python闭包例子_Python中闭包的简单介绍(附示例)

本篇文章给大家带来的内容是关于Python中闭包的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

一:简介

函数式编程不是程序必须要的,但是对于简化程序有很重要的作用。

Python中一切都是对象,函数也是对象a = 1

a = 'str'

a = func

二:闭包

闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+环境变量)

如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure),这个是最直白的解释!而且这个变量的值不会被模块中相同的变量值所修改!

三:闭包的作用

少使用全局变量,闭包可以避免使用全局变量

可以实现在函数外部调用函数内部的值:

print(f.__closure__[0].cell_contents)

# 返回闭包中环境变量的值!

模块操作是不能实现的!# ----------------------------------------------#

# 闭包

# ----------------------------------------------#

# 函数内部定义函数

def curve_pre():

def curve():

print("抛物线")

pass

return curve

# 不能直接调用函数内部的函数

# curve()

func = curve_pre()

func()

def curve_pre1():

a = 25 # 环境变量a的值在curve1外部

def curve1(x):

print("抛物线")

return a * x ** 2

return curve1 # 返回了的闭包

f = curve_pre1()

result = f(2)

print(result)

# 当在外部定义变量的时候,结果不会改变

a = 10

print(f(2))

print(f.__closure__) # 检测函数是不是闭包

print(f.__closure__[0].cell_contents) # 返回闭包中环境变量的值!

# ----------------------------------------------#

# 闭包的实例

# ----------------------------------------------#

def f1():

m = 10

def f2():

m = 20 # 局部变量

print("1:", m) # m = 20

print("2:", m) # m = 10

f2()

print("3:", m) # m = 10,臂包里面的值不会影响闭包外面的值

return f2

f1()

f = f1()

print(f.__closure__) # 判断是不是闭包

# ----------------------------------------------#

# 闭包解决一个问题

# ----------------------------------------------#

# 在函数内部修改全局变量的值计算某人的累计步数

# 普通方法实现

sum_step = 0

def calc_foot(step=0):

global sum_step

sum_step = sum_step + step

while True:

x_step = input('step_number:')

if x_step == ' ': # 输入空格结束输入

print('total step is ', sum_step)

break

calc_foot(int(x_step))

print(sum_step)

# 闭包方式实现----->少使用全局变量,闭包可以避免

def factory(pos):

def move(step):

nonlocal pos # 修改外部作用域而非全局变量的值

new_pose = pos + step

pos = new_pose # 保存修改后的值

return pos

return move

tourist = factory(0)

print(tourist(2))

print(tourist(2))

print(tourist(2))

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值