Python中闭包的简单介绍(附示例)


本文摘自php中文网,作者不言,侵删。

本篇文章给大家带来的内容是关于Python中闭包的简单介绍(附示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

一:简介
函数式编程不是程序必须要的,但是对于简化程序有很重要的作用。
Python中一切都是对象,函数也是对象

1

2

3

a = 1

 a = 'str'

 a = func

二:闭包

闭包是由函数及其相关的引用环境组合而成的实体(即:闭包=函数+环境变量)
如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure),这个是最直白的解释!而且这个变量的值不会被模块中相同的变量值所修改!

三:闭包的作用

少使用全局变量,闭包可以避免使用全局变量
可以实现在函数外部调用函数内部的值:
print(f.__closure__[0].cell_contents)
# 返回闭包中环境变量的值!
模块操作是不能实现的!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

# ----------------------------------------------#

# 闭包

# ----------------------------------------------#

# 函数内部定义函数

def curve_pre():

    def curve():

        print("抛物线")

        pass

    return curve

# 不能直接调用函数内部的函数

# curve()

func = curve_pre()

func()

def curve_pre1():

    a = 25  # 环境变量a的值在curve1外部

 

    def curve1(x):

        print("抛物线")

        return a * x ** 2

    return curve1       # 返回了的闭包

f = curve_pre1()

result = f(2)

print(result)

# 当在外部定义变量的时候,结果不会改变

a = 10

print(f(2))

print(f.__closure__)    # 检测函数是不是闭包

print(f.__closure__[0].cell_contents)    # 返回闭包中环境变量的值!

# ----------------------------------------------#

# 闭包的实例

# ----------------------------------------------#

def f1():

    m = 10

    def f2():

        m = 20  # 局部变量

        print("1:", m)  # m = 20

    print("2:", m)      # m = 10

    f2()

    print("3:", m)      # m = 10,臂包里面的值不会影响闭包外面的值

    return f2

f1()

f = f1()

print(f.__closure__)    # 判断是不是闭包

 

# ----------------------------------------------#

# 闭包解决一个问题

# ----------------------------------------------#

# 在函数内部修改全局变量的值计算某人的累计步数

# 普通方法实现

sum_step = 0

 

 

def calc_foot(step=0):

    global sum_step

    sum_step = sum_step + step

 

 

while True:

    x_step = input('step_number:')

    if x_step == ' ':   # 输入空格结束输入

        print('total step is ', sum_step)

        break

    calc_foot(int(x_step))

    print(sum_step)

 

# 闭包方式实现----->少使用全局变量,闭包可以避免

 

 

def factory(pos):

 

    def move(step):

        nonlocal pos    # 修改外部作用域而非全局变量的值

        new_pose = pos + step

        pos = new_pose  # 保存修改后的值

        return pos

 

    return move

 

 

tourist = factory(0)

print(tourist(2))

print(tourist(2))

print(tourist(2))

以上就是Python中闭包的简单介绍(附示例)的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python怎么把string变为hex

Python下递归遍历目录和文件的方法介绍

操作Python实现npy格式文件转换为txt文件

Python开发学习包括哪些内容

Python 怎么用for重复(循环)

Python的单线程多任务的实现

Python获取当前时间

mac系统可以学Python

Python怎么运行

Python适合做什么开发?

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...