1. 程式人生 > >Python列舉

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()

– 更多參見: – 聲 明:轉載請註明出處 – Last Updated on 2018-09-23 – Written by ShangBo on 2018-09-23 – End