标签:member ber 面向 usr traceback http pre tab user
注:python 3.x版本才能使用枚举格式:
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, in <module> class Weekday(Enum): File "/usr/lib/python3.4/enum.py", line 524, in unique (enumeration, alias_details))
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, in <module> print (Weekday.tusday > Weekday.friday ) TypeError: unorderable types: Weekday() > Weekday()
看到一个很好很好的Blog,这讲的内容,他的比廖某的还要简洁明了。很喜欢。我的怎么乱?我纯粹是做笔记,没想那么多,要改构造想多了反而浪费时间。
https://blog.csdn.net/xionghuixionghui/article/details/66476601
python Class:面向对象高级编程 Enum(枚举)、@unique
标签:member ber 面向 usr traceback http pre tab user
原文地址:http://blog.51cto.com/13502993/2147820