Python 闭包
2018-01-02 17:10
393 查看
闭包
闭包(closure)是函数式编程的重要的语法结构,Python也支持这一特性,下面就开始介绍Python中的闭包。 首先看看闭包的概念:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即使已经离开了创造它的环境也不例外。所以,闭包是由函数和与其相关的引用环境组合而成的实体。
在开始介绍闭包之前先看看Python中的namespace。
Python中的namespace
Python中通过提供
namespace来实现重名函数/方法、变量等信息的识别,其一共有三种 namespace,分别为:
local namespace: 作用范围为当前函数或者类方法
global namespace: 作用范围为当前模块
build-in namespace: 作用范围为所有模块
当函数/方法、变量等信息发生重名时,Python会按照 “local namespace -> global namespace -> build-in namespace”的顺序搜索用户所需元素,并且以第一个找到此元素的 namespace 为准。
同时,Python中的内建函数locals()和globals()可以用来查看不同namespace中定义的元素。
看一个例子:
s = "string in global" num = 99 def numFunc(a, b): num = 100 print("numFunc的s: ", s) def addFunc(a, b): s = "string in addFunc" print("addFunc的 s: ", s) print("addFunc的num: ", num) print("addFunc的locals : ", locals()) print() return "%d + %d = %d" % (a, b, a + b) print("numFunc的locals: ", locals()) print() return addFunc(a, b) numFunc(3, 6) print("全局: ", globals())
结果:
numFunc的s: string in global numFunc的locals: {'addFunc': <function numFunc.<locals>.addFunc at 0x0317E8A0>, 'b': 6, 'a': 3, 'num': 100} addFunc的 s: string in addFunc addFunc的num: 100 addFunc的locals : {'s': 'string in addFunc', 'b': 6, 'a': 3, 'num': 100} 全局: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0301A310>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:\\Python\\PythonProject\\flys\\qq.py', '__cached__': None, 's': 'string in global', 'num': 99, 'numFunc': <function numFunc at 0x0317E8E8>} [Finished in 0.4s]
代码中通过locals()和globals()获取了不同namespace中定义的元素,当在”numFunc”函数中访问s变量的时候,由于local namespace中没有定义s,所以会找到global中的s;但是,由于”addFunc”的local namespace中有s,所以可以直接使用。
Python创建闭包
下面通过一个例子一步一步分析一下Python如何实现闭包。#定义一个函数 def test(number): #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包 def test_in(number_in): print("in test_in 函数, number_in is %d"%number_in) return number+number_in #其实这里返回的就是闭包的结果 return test_in #给test函数赋值,这个20就是给参数number ret = test(20) #注意这里的100其实给参数number_in print(ret(100)) #注意这里的200其实给参数number_in print(ret(200))
结果:
in test_in 函数, number_in is 100 120 in test_in 函数, number_in is 200 220
在Python中创建一个闭包可以归结为以下三点:
闭包函数必须有内嵌函数
内嵌函数需要引用该嵌套函数上一级namespace中的变量
闭包函数必须返回内嵌函数
通过这三点,就可以创建一个闭包.
__closure__
属性
在Python中,函数对象有一个__closure__属性,我们可以通过这个属性看看闭包的一些细节。
def greeting_conf(prefix): def greeting(name): print(prefix, name) return greeting mGreeting = greeting_conf("Good Morning") print(dir(mGreeting)) print(mGreeting.__closure__) print(type(mGreeting.__closure__[0])) print(mGreeting.__closure__[0].cell_contents)
通过
__closure__属性看到,它对应了一个tuple,tuple的内部包含了cell类型的对象。
对于这个例子,可以得到cell的值(内容)为”Good Morning”,也就是变量”prefix”的值。
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] (<cell at 0x012AA330: str object at 0x02E47570>,) <class 'cell'> Good Morning
从这里可以看到闭包的原理,当内嵌函数引用了包含它的函数(enclosing function)中的变量后,这些变量会被保存在enclosing function的
__closure__属性中,成为enclosing function本身的一部分;也就是说,这些变量的生命周期会和enclosing function一样。
闭包再理解
内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包。闭包只是在表现形式上跟函数类似,但实际上不是函数。# closure.py def counter(start=0): count=[start] def incr(): count[0] += 1 return count[0] return incr
启动python解释器
>>>import closeure >>>c1=closeure.counter(5) >>>print(c1()) 6 >>>print(c1()) 7 >>>c2=closeure.counter(100) >>>print(c2()) 101 >>>print(c2()) 102
nonlocal访问外部函数的局部变量(python3)
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())
看一个闭包的实际例子:
def line_conf(a, b): def line(x): return a*x + b return line line1 = line_conf(1, 1) line2 = line_conf(4, 5) print(line1(5)) print(line2(5))
这个例子中,函数line与变量a,b构成闭包。在创建闭包的时候,我们通过line_conf的参数a,b说明了这两个变量的取值,这样,我们就确定了函数的最终形式(y = x + 1和y = 4x + 5)。我们只需要变换参数a,b,就可以获得不同的直线表达函数。由此,我们可以看到,闭包也具有提高代码可复用性的作用。
如果没有闭包,我们需要每次创建直线函数的时候同时说明a,b,x。这样,我们就需要更多的参数传递,也减少了代码的可移植性。
闭包思考:
闭包似优化了变量,原来需要类对象完成的工作,闭包也可以完成
由于闭包引用了外部函数的局部变量,则外部函数的局部变量没有及时释放,消耗内存
相关文章推荐
- 21.python中的闭包和装饰器
- 16、Python中的闭包、上下文、类的专有方法及鸭子类型
- Python中的闭包
- Python闭包与javascript闭包比较
- python中的闭包
- 【Python笔记】Python的几个高级语法概念浅析:lambda表达式 && 闭包 && 装饰器
- Python中的闭包-closure
- c语言,python实现汉诺塔,关于闭包的思考
- python闭包小例子
- Python学习笔记-闭包
- python核心高级学习总结8------动态性、__slots__、生成器、迭代器、装饰、闭包
- Python中函数的闭包
- python闭包详解
- python-闭包
- python之嵌套函数与闭包
- Python闭包的代码
- python中的闭包
- Python Enclosing作用域、闭包、装饰器
- python基础,计数器函数(闭包的使用)
- python 学习(十九)之浅谈闭包