1. Python闭包是什么
在python中有函数闭包的概念,这个概念是什么意思呢,查看Wikipedia的说明如下:
“
In programming languages, closures (also lexical closures or function closures) are a technique for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or storage location to which the name was bound when the closure was created. A closure—unlike a plain function—allows the function to access those captured variables through the closure's reference to them, even when the function is invoked outside their scope.
” —— 原文链接:https://en.wikipedia.org/wiki/Closure_(computer_programming)
看上去概念很多,下面我们通俗的讲一下
假设我有个求x^n的函数如下
def pow(x, n):
res = 1
for i in range(n):
res *= x
return res
class Pow(object):
def __init__(self, n):
self.n = n
def __call__(self, x):
res = 1
for i in range(self.n): # 引用对象成员
res *= x
return res
pow2 = Pow(2)
len2d = pow2(20) + pow2(30)
pow3 = Pow(3)
len3d = pow3(20) + pow3(30) + pow3(40)
(例3)