1 # ----------------------------------------------#
2 # 閉包
3 # ----------------------------------------------#
4 # 函數內部定義函數
5
6
7 def curve_pre():
8 def curve():
9 print("拋物線")
10 pass
11 return curve
12
13
14 # 不能直接調用函數內部的函數
15 # curve()
16 func = curve_pre()
17 func()
18
19
20 def curve_pre1():
21 a = 25 # 環境變量a的值在curve1外部
22
23 def curve1(x):
24 print("拋物線")
25 return a * x ** 2
26 return curve1 # 返回了的閉包
27
28
29 f = curve_pre1()
30
31 result = f(2)
32 print(result)
33
34 # 當在外部定義變量的時候,結果不會改變
35 a = 10
36 print(f(2))
37
38 print(f.__closure__) # 檢測函數是否是閉包
39 print(f.__closure__[0].cell_contents) # 返回閉包中環境變量的值!
40
41 # ----------------------------------------------#
42 # 閉包的實例
43 # ----------------------------------------------#
44
45
46 def f1():
47 m = 10
48
49 def f2():
50 m = 20 # 局部變量
51 print("1:", m) # m = 20
52 print("2:", m) # m = 10
53 f2()
54 print("3:", m) # m = 10,臂包裏面的值不會影響閉包外面的值
55 return f2
56
57
58 f1()
59 f = f1()
60 print(f.__closure__) # 判斷是否是閉包
61
62 # ----------------------------------------------#
63 # 閉包解決一個問題
64 # ----------------------------------------------#
65 # 在函數內部修改全局變量的值計算某人的累計步數
66 # 普通方法實現
67 sum_step = 0
68
69
70 def calc_foot(step=0):
71 global sum_step
72 sum_step = sum_step + step
73
74
75 while True:
76 x_step = input('step_number:')
77 if x_step == ' ': # 輸入空格結束輸入
78 print('total step is ', sum_step)
79 break
80 calc_foot(int(x_step))
81 print(sum_step)
82
83 # 閉包方式實現----->少使用全局變量,閉包能夠避免
84
85
86 def factory(pos):
87
88 def move(step):
89 nonlocal pos # 修改外部做用域而非全局變量的值
90 new_pose = pos + step
91 pos = new_pose # 保存修改後的值
92 return pos
93
94 return move
95
96
97 tourist = factory(0)
98 print(tourist(2))
99 print(tourist(2))
100 print(tourist(2))