为什么要使用闭包(closures)

闭包是一个难学的概念,首先要搞清楚为什么需要闭包?其实闭包的出现往往是函数式编程的语言里,在面向对象的编程语言里是可以不需要闭包的。因为闭包作用如下:
1. 避免使用全局变量,实现数据隐藏和保持,也就是面向对象的特性:封装。
2. 当成员变量比较少,以及方法只有一个时,比类更简单实现。
3. 数据和函数一起封装,适应异步或并发运行。


什么时候定义了一个闭包
当在一个函数里嵌套定义一个函数时,就会产生一个闭包,因此定义一个闭包需要下面几个条件:
1. 嵌套函数定义(函数内定义函数)。
2. 最内层嵌套函数访问函数外的局部变量。
3. 函数返回内嵌套函数对象。


如下面例子:

#python 3.6
def add_conf():
    b = 10
    def add(x):
        return x + b

    b = 1
    return add
#
my_conf = add_conf()
print(my_conf(1))
输出结果如下:

2
又或者如下面的例子:

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier

# Multiplier of 3
times3 = make_multiplier_of(3)

# Multiplier of 5
times5 = make_multiplier_of(5)

# Output: 27
print(times3(9))

# Output: 15
print(times5(3))

# Output: 30
print(times5(times3(2)))
结果输出如下:

27
15
30
从上面这个例子里,可以看到局部变量n会保存起来,并且在这里并没有使用全局变量,就可以达到这个目标,并且数据也可以隐藏起来。

在python里可以通过__closure__来查看闭包时保存的环境变量的值,如下例子:

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier

# Multiplier of 3
times3 = make_multiplier_of(3)

# Multiplier of 5
times5 = make_multiplier_of(5)

# Output: 27
print(times3(9))

# Output: 15
print(times5(3))

# Output: 30
print(times5(times3(2)))

print(times3.__closure__[0].cell_contents)
print(times5.__closure__[0].cell_contents)
结果输出如下:

27
15
30
3
5

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672







你可能感兴趣的:(milang(小语))