装饰器一:闭包函数

一、闭包函数的大前提:

  闭包函数 = 名称空间与作用域 + 函数嵌套 + 函数对象

          核心点:名字的查询关系是以函数的定义阶段为准

二、什么是闭包函数:

  “闭”函数指的该函数是内嵌函数。

  “包”函数指的该函数包含对外层函数作用域名字的引用(不是对全局作用域)。

 1 def outSide(x):
 2     x="11111"
 3     def inSide():
 4         print(x)
 5     return inSide
 6 
 7 x="22222"
 8 f = outSide()
 9 f()
10 
11 def foo():
12     x="33333"
13     f()

  不管 f() 在何处调用,x的值均为其外层函数outSide的作用域,值为111111,即outSide和inSide为一个整体。

三、为何要有闭包函数==>闭包函数的应用

1 def outSide(x):
2     def inSide():
3         print(x)
4     return inSide
5 
6 f = outSide("1111111")
7 f()

 闭包函数为我们提供了函数传参的第二种方式

原文地址:https://www.cnblogs.com/xjklmycw/p/15017670.html