闭包的定义
闭包就是函数内部定义的函数。
闭包的逻辑
理解闭包的逻辑之后,有了一定python基础的都可以很容易写出闭包。下面通过案例来讲一下闭包的逻辑。
def discount(x): if x<0.5 or x>1: return None def count(prince, number): result = prince * number pay = result * x print(f'总价是{result}元,实付{pay}元') return countdiscount(0.8)(2.88, 100)out:总价是288.0元,实付230.4元
以上代码是销售商品时经常遇到的案例,discount函数是外层函数,用来检测打折数字是否合理。count是内层函数,用来计算总金额和实付金额。
python解释器遇到def discount时会在全局命名空间增加一个discount对象,它的值指向discount函数内的代码块。此时discount函数没有运行。
在遇到discount(0.8)(2.88, 100)时开始运行函数discount(0.8),在遇到def count会在discount的局部命名空间增加一个count对象,它的值指向count函数内的代码块。在遇到return count时会把count对象返回给discount(0.8)(2.88,100)。此时discount(0.8)部分已经运行完毕,接下来运行的是count(2.88,100)。count(2.88,100)内部代码块运行完毕后,整个闭包函数运行完毕。

闭包的扩展
我们可以通过如下的方式对闭包进行扩展,更加方便使用:
def discount(x): if x < 0.5 or x > 1: print('折扣数字不合理。') return def count(prince, number): result = prince * number pay = result * x print(f'总价是{result}元,实付{pay}元') return countgoldcard = discount(0.7)silvercard = discount(0.9)commomcard = discount(1)goldcard(2.88, 100)silvercard(2.88, 100)commomcard(2.88,100)print(id(goldcard))print(id(silvercard))print(id(commomcard))out:总价是288.0元,实付201.6元总价是288.0元,实付259.2元总价是288.0元,实付288.0元198680270409619870813683361987081368192
将外层函数加参数赋值给另外一个变量,相当于定义了一个新的函数,提高了代码复用率。上述goldcard、silvercard、commomcard这3个函数虽然都指向了discount函数,但是因为它们的参数不同,实际上是3个独立的对象,可以看到它们的id各不相同。