Python中的枚举是使用名为“enum”的模块实现的。枚举是使用类创建的。枚举具有与之关联的名称和值。
枚举的属性:
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
# printing enum member as string
print(Season.SPRING)
# printing name of enum member using "name" keyword
print(Season.SPRING.name)
# printing value of enum member using "value" keyword
print(Season.SPRING.value)
# printing the type of enum member using type()
print(type(Season.SPRING))
# printing enum member as repr
print(repr(Season.SPRING))
# printing all enum member using "list" keyword
print(list(Season))
输出
Season.SPRING
SPRING
1
<enum 'Season'>
<Season.SPRING: 1>
[<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]
可以通过两种方式访问枚举成员:
也可以使用“name”或“value”关键字访问单独的值或名称。
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
# Accessing enum member using value
print("The enum member associated with value 2 is : ", Season(2).name)
# Accessing enum member using name
print("The enum member associated with name AUTUMN is : ", Season['AUTUMN'].value)
输出
The enum member associated with value 2 is : SUMMER
The enum member associated with name AUTUMN is : 3
在这个例子中,我们将使用for循环来打印Enum类的所有成员。
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
for season in (Season):
print(season.value,"-",season)
输出
1 - Season.SPRING
2 - Season.SUMMER
3 - Season.AUTUMN
4 - Season.WINTER
import enum
# creating enumerations using class
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
# Hashing enum member as dictionary
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'
# checking if enum values are hashed successfully
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
print("Enum is hashed")
else:
print("Enum is not hashed")
输出
Enum is hashed
import enum
# creating enumerations using class
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
# Comparison using "is"
if Animal.dog is Animal.cat:
print("Dog and cat are same animals")
else:
print("Dog and cat are different animals")
# Comparison using "!="
if Animal.lion != Animal.cat:
print("Lions and cat are different")
else:
print("Lions and cat are same")
输出
Dog and cat are different animals
Lions and cat are different