Python中闭包的简单介绍(附示例)
本篇文章给大家带来的内容是关于python中闭包的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
一:简介
函数式编程不是程序必须要的,但是对于简化程序有很重要的作用。
Python中一切都是对象,函数也是对象
a = 1 a = 'str' a = func
二:闭包
闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+环境变量)
如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure),这个是最直白的解释!而且这个变量的值不会被模块中相同的变量值所修改!
三:闭包的作用
立即学习“Python免费学习笔记(深入)”;
少使用全局变量,闭包可以避免使用全局变量
可以实现在函数外部调用函数内部的值:
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 = 10print(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 f2f1()f = f1()print(f.__closure__) # 判断是不是闭包# ----------------------------------------------## 闭包解决一个问题# ----------------------------------------------## 在函数内部修改全局变量的值计算某人的累计步数# 普通方法实现sum_step = 0def calc_foot(step=0): global sum_step sum_step = sum_step + stepwhile 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 movetourist = factory(0)print(tourist(2))print(tourist(2))print(tourist(2))