python: enum

Python的Enum类
举例

>>> from enum import Enum
>>> Weekday = Enum('Weekday', ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'))
>>> for name, member in Weekday.__members__.items():
...     print(name, member.value) #value属性则是自动赋给成员的int常量,默认从1开始计数。
...
Sun 1 
Mon 2
Tue 3
Wed 4
Thu 5
Fri 6
Sat 7
>>>

可以直接使用Weekday.Sun来引用一个常量

>>> Weekday.Sun
.Sun: 1>
>>>

还可以自定义Enum类:

>>> from enum import Enum, unique
>>> @unique #装饰器@unique检查重复值
... class Weekday(Enum):
...     Sun = 0 #赋值
...     Mon = 1
...     Tue = 2
...     Wed = 3
...     Thu = 4
...     Fri = 5
...     Sat = 6
...
>>> for name, no in Weekday.__members__.items():
...     print(name, no.value)
...
Sun 0 
Mon 1
Tue 2
Wed 3
Thu 4
Fri 5
Sat 6
>>>

查看常量和常量对应的值:

>>> Weekday.Sun
<Weekday.Sun: 0>
>>> Weekday.Sun.value
0
>>> Weekday['Sun']
<Weekday.Sun: 0>
>>> Weekday(0)
<Weekday.Sun: 0>
>>>
>>>> s = Weekday.Sun #可以赋值给一个标量变量,通过变量操作
>>> s
<Weekday.Sun: 0>
>>> s.value
0

你可能感兴趣的:(python)