一、枚举
1.1 枚举的表示
In [31]:
from enum import Enum
class COLOUR(Enum):
YELLOW =1
GREEN =2
BLACK = 3
RED = 4
print(COLOUR.YELLOW)
COLOUR.YELLOW
1.2 枚举的优势和特点(相比于字典)
枚举不可变,枚举不允许相同的标签
1.3 枚举的操作
1.3.1 获取枚举值
In [32]:
COLOUR.YELLOW.value
Out[32]:
1
1.3.2 获取枚举标签的名字
In [33]:
COLOUR.YELLOW.name
Out[33]:
'YELLOW'
1.3.3 枚举的类型
In [34]:
COLOUR.YELLOW
Out[34]:
<COLOUR.YELLOW: 1>
1.3.4 枚举的遍历
In [35]:
for v in COLOUR:
print(v)
COLOUR.YELLOW
COLOUR.GREEN
COLOUR.BLACK
COLOUR.RED
1.4 枚举的比较
In [36]:
result = COLOUR.GREEN = COLOUR.YELLOW
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-36-f77b40ebd0e6> in <module>()
----> 1 result = COLOUR.GREEN = COLOUR.YELLOW
D:\python2713\lib\anaconda_install\envs\course_py35\lib\enum.py in __setattr__(cls, name, value)
309 member_map = cls.__dict__.get('_member_map_', {})
310 if name in member_map:
--> 311 raise AttributeError('Cannot reassign members.')
312 super().__setattr__(name, value)
313
AttributeError: Cannot reassign members.
In [37]:
result = COLOUR.GREEN is COLOUR.YELLOW
result
Out[37]:
False
1.5 枚举的转换
代码显示定义枚举类,数据库用数值,如何将数值转换为枚举?
In [38]:
a = 1
print(COLOUR(a))
COLOUR.YELLOW
1.6枚举的限定
业务需求枚举的值为整数,且值不能相同,该如何操作?
In [ ]:
from enum import IntEnum,unquire
@unique
二、闭包
适用场景:编写包和类库,编写业务逻辑通常不用闭包
2.1 概念
In [40]:
def curve_pre():
a = 25
def cureve(x):
return a*x*x
return cureve
a = 10
f =curve_pre()
f(2)
f.__closure__[0].cell_contents # 为保存的局部变量的值
Out[40]:
25
闭包:函数+环境变量整体返回
2.2 示例
In [41]:
def f1():
a = 10
def f2():
a = 20 # 局部变量
print("1"+" "+str(a))
print("2"+" "+str(a))
f2()
print("3"+" "+str(a))
f1()
2 10
1 20
3 10
第一次打印的是 a=10,第二次打印的是a=20(打印局部变量),第三次打印a =10(局部变量并不能改变外面a=10的值)
这并不是一个闭包,因为f2()并没有调用a=10,反而调用f2内部的a=20,所以没有构成闭包。
闭包内的函数需要引用定义的变量
2.3 闭包解决的问题
In [42]:
origin = 0
def factory(pos):
def go(step):
nonlocal pos
new_pos = pos + step
pos = new_pos
return new_pos
return go
tourist = factory(origin)
tourist(2)
print(tourist.__closure__[0].cell_contents)
tourist(3)
print(tourist.__closure__[0].cell_contents)
tourist(5)
print(tourist.__closure__[0].cell_contents)
2
5
10