– Start
枚举通常用来定义类别,如性别有男,女等。
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)
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