python每周一库之enum

enum类型可以定义一些有关系的常量的集合,很多开发语言中都有enum类型,python中也不例外。下面介绍下python中enum类型的各种使用姿势。

首先,附上python3.6官方文档:
python3.6官方文档

下面介绍enum的使用

1.定义enum


from enum import Enum

class Test(Enum):
    """职业类型
    """
    PLAYER = 1
    STUDENT = 2
    ENGINEER = 3

2.enum取值方式


# 1)通过成员名称获取成员
Test['PLAYER']
# output
<Test.PLAYER: 1>

# 2)通过成员值获取成员
Test(1)
# output
<Test.PLAYER: 1>

# 3)通过成员获取名称和值
print(Test.STUDENT.name)
print(Test.STUDENT.value)
# output
STUDENT
2

3.enum支持迭代


for t in Test:
    print(t)

# output
Test.PLAYER
Test.STUDENT
Test.ENGINEER

4.enum成员是可hash的,可以作为dict的key


d1 = dict()
d1[Test.PLAYER] = 'tm'
d1[Test.STUDENT] = 'puple'
d1
# output
{<Test.PLAYER: 1>: 'tm', <Test.STUDENT: 2>: 'puple'}

5.默认enum中可以有多个名称对应同一个值


from enum import Enum

class Test(Enum):
    """职业类型
    """
    PLAYER = 1
    STUDENT = 2
    ENGINEER = 3
    DOCTOR = 3

print(Test.ENGINEER)
print(Test.DOCTOR)
# output
Test.ENGINEER
Test.ENGINEER

print(Test(3))
# output
Test.ENGINEER

# 从上面的输出可以看出,对于同一个值,
# 后创建的常量名是作为第一次创建的常量的别名存在的

# 可以使用unique来约束,一个值只能对应一个名称
from enum import Enum, unique

@unique
class Test(Enum):
    """职业类型
    """
    PLAYER = 1
    STUDENT = 2
    ENGINEER = 3
    DOCTOR = 3

# 上面这样创建后会抛出异常
# ValueError: duplicate values found in <enum 'Test'>: DOCTOR -> ENGINEER

6.enum自动生成值


from enum import Enum, unique, auto

@unique
class Test(Enum):
    """职业类型
    """
    PLAYER = auto()
    STUDENT = auto()
    ENGINEER = auto()
    DOCTOR = auto()

for t in Test:
    print(t, t.value)

# output
Test.PLAYER 1
Test.STUDENT 2
Test.ENGINEER 3
Test.DOCTOR 4

7.自定义自动生成值的规则


from enum import Enum, unique

class AutoValue(Enum):
    def _generate_next_value_(name, start, count, last_values):        
        return name

@unique
class Test(AutoValue):
    """职业类型
    """
    PLAYER = auto()
    STUDENT = auto()
    ENGINEER = auto()
    DOCTOR = auto()

for t in Test:
    print(t, t.value)

# output
Test.PLAYER PLAYER
Test.STUDENT STUDENT
Test.ENGINEER ENGINEER
Test.DOCTOR DOCTOR

8.快速创建enum的方法


Test = Enum('Test', [('PLAYER', 4), ('STUDENT', 5), ('ENGINEER', 6)])
for t in Test:
    print(t, t.value)

# output
Test.PLAYER 4
Test.STUDENT 5
Test.ENGINEER 6

上面就是python中enum的常用方式。