Python枚举

– Start

点击此处观看本系列配套视频。


什么是枚举?

枚举通常用来定义类别,如性别有男,女等。

例子1

from enum import Enum

# 定义枚举
class Gender(Enum):
    MALE = 1
    FEMALE = 2
    UNKNOW = 3


# 使用枚举
g = Gender.FEMALE
g = Gender(1)
g = Gender['FEMALE']
print(g)
print(g.name)
print(g.value)


# 迭代枚举
for g in Gender:
    print(g)

例子2

from enum import Enum

# 定义枚举
#Gender = Enum('Gender', 'MALE FEMALE UNKNOW')
Gender = Enum('Gender', [('MALE',1), ('FEMALE',2), ('UNKNOW',3)])

# 使用枚举
g = Gender.FEMALE
g = Gender(1)
g = Gender['FEMALE']
print(g)
print(g.name)
print(g.value)


# 迭代枚举
for g in Gender:
    print(g)

自动生成值

from enum import Enum, auto

# 如果不关心值,可以自动生成
class Gender(Enum):
    MALE = auto()
    FEMALE = auto()
    UNKNOW = auto()

– 更多参见:Python 精萃
– 声 明:转载请注明出处
– Last Updated on 2018-09-23
– Written by ShangBo on 2018-09-23
– End

你可能感兴趣的:(Python)