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)