在Python中,枚舉和我們在對象中定義的類變量時一樣的,每一個類變量就是一個枚舉項,訪問枚舉項的方式爲:類名加上類變量,像下面這樣:
class color():
YELLOW = 1
RED = 2
GREEN = 3
PINK = 4
# 訪問枚舉項
print(color.YELLOW) # 1
雖然這樣是可以解決問題的,但是並不嚴謹,也不怎麼安全,比如:
1、枚舉類中,不應該存在key相同的枚舉項(類變量)
2、不允許在類外直接修改枚舉項的值
class color():
YELLOW = 1
YELLOW = 3 # 注意這裏又將YELLOW賦值爲3,會覆蓋前面的1
RED = 2
GREEN = 3
PINK = 4
# 訪問枚舉項
print(color.YELLOW) # 3
# 但是可以在外部修改定義的枚舉項的值,這是不應該發生的
color.YELLOW = 99
print(color.YELLOW) # 99
解決方案:使用enum模塊
enum模塊是系統內置模塊,可以直接使用import導入,但是在導入的時候,不建議使用import enum將enum模塊中的所有數據都導入,一般使用的最多的就是enum模塊中的Enum、IntEnum、unique這幾項
# 導入枚舉類
from enum import Enum
# 繼承枚舉類
class color(Enum):
YELLOW = 1
BEOWN = 1
# 注意BROWN的值和YELLOW的值相同,這是允許的,此時的BROWN相當於YELLOW的別名
RED = 2
GREEN = 3
PINK = 4
class color2(Enum):
YELLOW = 1
RED = 2
GREEN = 3
PINK = 4
使用自己定義的枚舉類:
print(color.YELLOW) # color.YELLOW
print(type(color.YELLOW)) # <enum 'color'>
print(color.YELLOW.value) # 1
print(type(color.YELLOW.value)) # <class 'int'>
print(color.YELLOW == 1) # False
print(color.YELLOW.value == 1) # True
print(color.YELLOW == color.YELLOW) # True
print(color.YELLOW == color2.YELLOW) # False
print(color.YELLOW is color2.YELLOW) # False
print(color.YELLOW is color.YELLOW) # True
print(color(1)) # color.YELLOW
print(type(color(1))) # <enum 'color'>
注意事項如下:
1、枚舉類不能用來實例化對象
2、訪問枚舉類中的某一項,直接使用類名訪問加上要訪問的項即可,比如 color.YELLOW
3、枚舉類裏面定義的Key = Value,在類外部不能修改Value值,也就是說下面這個做法是錯誤的
color.YELLOW = 2 # Wrong, can't reassign member
4、枚舉項可以用來比較,使用==,或者is
5、導入Enum之後,一個枚舉類中的Key和Value,Key不能相同,Value可以相,但是Value相同的各項Key都會當做別名,
6、如果要枚舉類中的Value只能是整型數字,那麼,可以導入IntEnum,然後繼承IntEnum即可,注意,此時,如果value爲字符串的數字,也不會報錯:
from enum import IntEnum
7、如果要枚舉類中的key也不能相同,那麼在導入Enum的同時,需要導入unique函數
from enum import Enum, unique