大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
注:python 3.x版本才能使用
专注于为中小企业提供网站设计、网站建设服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业上蔡免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了近1000家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
枚举格式:
from enum import Enum
新类名 = Enum(变量统称名,(变量1,变量2....))
Month = Enum('month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
1.
seasons = ['Spring', 'Summer', 'Fall', 'Winter'] print (list(enumerate(seasons)))
运行结果:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
2.
from enum import Enum Month = Enum('month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)
运行结果:
Jan => month.Jan , 1 Feb => month.Feb , 2 Mar => month.Mar , 3 Apr => month.Apr , 4 May => month.May , 5 Jun => month.Jun , 6 Jul => month.Jul , 7 Aug => month.Aug , 8 Sep => month.Sep , 9 Oct => month.Oct , 10 Nov => month.Nov , 11 Dec => month.Dec , 12
3. 当Class中有重复值时,会返回第一个,其他忽略
from enum import Enum class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 #print (Weekday(1)) for n in Weekday: print (n)
运行结果:
Weekday.monday Weekday.wensdday Weekday.thursday Weekday.friday
手动打Enum值时,一不小心打错了怎么办,又得一个个找,真麻烦。所以,有人想,如果有个方法能够检查重复值就好了,于是:@unique就出来了
from enum import Enum, @unique class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 print (Weekday(1))
运行结果:
Traceback (most recent call last): File "/usercode/file.py", line 7, inclass Weekday(Enum): File "/usr/lib/python3.4/enum.py", line 524, in unique (enumeration, alias_details)) ValueError: duplicate values found in : tusday -> monday
4.有人也在想,我就是不改咋地!我能不能通过另一个方法把成员都打印出来?于是:__members__就出来了
from enum import Enum class Weekday(Enum): monday = 1 tusday = 1 wensdday = 3 thursday = 9 friday = 5 for n,y in Weekday.__members__.items(): print (n, '--', y, '--', y.value) f = Weekday.thursday print (f.value)
运行结果:
monday -- Weekday.monday -- 1 tusday -- Weekday.tusday -- 1 wensdday -- Weekday.wensdday -- 3 thursday -- Weekday.thursday -- 9 friday -- Weekday.friday -- 5 9
5.枚举比较:不能比大小!!能比同值
from enum import Enum, unique #@unique class Weekday(Enum): monday = 1 tusday = 1 wensdday =3 thursday =9 friday =5 print (Weekday.monday == Weekday.wensdday) print (Weekday.tusday is Weekday.friday ) print (Weekday.tusday > Weekday.friday )
运行结果:
False False Traceback (most recent call last): File "/usercode/file.py", line 16, inprint (Weekday.tusday > Weekday.friday ) TypeError: unorderable types: Weekday() > Weekday()
看到一个很好很好的Blog,这讲的内容,他的比廖某的还要简洁明了。很喜欢。我的怎么乱?我纯粹是做笔记,没想那么多,要改构造想多了反而浪费时间。
https://blog.csdn.net/xionghuixionghui/article/details/66476601