1. 程式人生 > >Python函數式編程之閉包

Python函數式編程之閉包

問題 cto lob num ret ber 全局變量 bre mil

-------------------------函數式編程之*******閉包------------------------
Note:

一:簡介
函數式編程不是程序必須要的,但是對於簡化程序有很重要的作用。
Python中一切都是對象,函數也是對象
a = 1
a = ‘str‘
a = func

二:閉包
閉包是由函數及其相關的引用環境組合而成的實體(即:閉包=函數+環境變量)
如果在一個內部函數裏,對在外部作用域(但不是在全局作用域)的變量進行引用,
那麽內部函數就被認為是閉包(closure),這個是最直白的解釋!
而且這個變量的值不會被模塊中相同的變量值所修改!

三:閉包的作用
少使用全局變量,閉包可以避免使用全局變量
可以實現在函數外部調用函數內部的值:
print(f.__closure__[0].cell_contents)
# 返回閉包中環境變量的值!
模塊操作是不能實現的!
CODE:

  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))

 

Python函數式編程之閉包