1. 程式人生 > 實用技巧 >Python入門學習筆記9:Python高階語法與用法-列舉、函數語言程式設計<閉包>

Python入門學習筆記9:Python高階語法與用法-列舉、函數語言程式設計<閉包>

  1 #Python高階語法與用法
  2 #列舉
  3 from enum import Enum, IntEnum,unique
  4 
  5 
  6 class VIP(Enum):
  7     YELLOW = 1
  8     GREEN = 2
  9     BLACK = 3
 10     RED = 4
 11 
 12 class VIP1(Enum):
 13     YELLOW = 1
 14     YELLOW_ALIAS = 1#別名
 15     GREEN = 2
 16     BLACK = 3
 17     RED = 4
 18 
 19
@unique#裝飾器:作用為鑑別若常量有相同時會進行報錯處理 20 class VIP2(IntEnum):#整數型限制 21 YELLOW = 1 22 GREEN = 2 23 BLACK = 3 24 RED = 4 25 26 27 print("name:",VIP.YELLOW.name,",value:",VIP.YELLOW.value) 28 #變數 29 yellow = 1 30 green = 2 31 #字典 32 {'yellow':1,'green':2} 33 #類下的類變數 34 35 36
class TypeDiamond(): 37 yellow = 1 38 green = 2 39 40 """ 41 列舉的特點: 42 常量(不可變)、防止相同值的功能 43 列舉中的變數名稱不能重複 44 常量相同,變數不同時 45 列舉型別無法例項化的 46 設計模式(23中設計模式):單例模式 47 """ 48 print(VIP1.YELLOW) 49 print(type(VIP.GREEN.name))#<class 'str'> 50 print(type(VIP.GREEN))#<enum 'VIP'>
51 print(VIP['GREEN'])#VIP.GREEN 52 53 for vip in VIP: 54 print(vip) 55 for vip1 in VIP1.__members__.values():#遍歷時包含別名 56 print(vip1) 57 print(vip1.value) 58 59 result = VIP.GREEN == VIP1.GREEN 60 result1 = VIP.GREEN is VIP.GREEN 61 print(result,result1)#False True 62 63 64 a = 1 65 print(VIP(a))#VIP.YELLOW 66 if VIP(a) == VIP.YELLOW: 67 print("VIP YELLOW") 68 if VIP(a) == VIP.BLACK: 69 print("VIP BLACK")#VIP YELLOW 70 71 #函數語言程式設計 72 73 #Python一切皆物件 74 #閉包 = 函式+環境變數(函式定義的時候) 75 76 77 def curve_pre(): 78 a1 = 25 79 80 def curve(x): 81 return a1*x*x 82 return curve 83 84 a2 = 10 85 f = curve_pre() 86 f(2)#等價於curve(2) 87 print(type(f),f(2),f.__closure__,f.__closure__[0].cell_contents)#<class 'function'> 100 (<cell at 0x10488a790: int object at 0x10455cda0>,) 25 88 89 a3 = 10 90 91 92 def f3(x): 93 return a3 * x * x 94 95 96 print(f3(2)) 97 98 #閉包的事例 99 100 101 def f1(): 102 a4 = 10#此處為該閉包的環境變數 103 104 def f2(): 105 #a = 20 #a此處將被Python認為是一個區域性變數(無法呼叫外部環境變數導致無法形成閉包,所以此時不能將a進行賦值) 106 #print(a) 107 return a4 108 #print(a)#第一步 109 #f2()#第二步 110 #print(a)#第三步 111 return f2 112 113 114 f1 = f1() 115 print('f1:',f1,',f.__closure__:',f1.__closure__) 116 117 118 origin = 0 119 120 121 def go(step): 122 global origin #global關鍵字定義全域性變數且記錄並累加 123 new_pos = origin +step 124 origin = new_pos 125 return origin 126 127 128 print(go(2)) 129 print(go(3)) 130 print(go(6)) 131 132 origin1 = 0 133 134 135 def factory(pos): 136 def go1(step): 137 nonlocal pos#不是本地的全域性變數 138 new_pos = pos + step 139 pos = new_pos 140 return new_pos 141 return go1 142 143 144 tourist = factory(origin1) 145 print(tourist(2)) 146 print(tourist.__closure__[0].cell_contents) 147 print(tourist(3)) 148 print(tourist.__closure__[0].cell_contents) 149 print(tourist(6)) 150 print(tourist.__closure__[0].cell_contents)