Python 模拟枚举类型
先来看一段Python代码:
class weather() {
SUNNY = "sunny"
WINDY = "windy"
RAINY = "rainy"
}
print(weather.SUNNY) # 输出枚举对象
乍一看,好像很简单,对不对?我们只是声明了一个类变量(class),并且用print()
函数来调用类变量中的一个变量。but,这个代码是有问题的。
class weather() {
SUNNY = "sunny"
WINDY = "windy"
RAINY = "rainy"
SUNNY = "windy"
}
print(weather.SUNNY) # 输出的值是 windy
weather.SUNNY = "rainy"
print(weather.SUNNY) # 输出的值是 rainy
通常情况,一个类中的枚举项不能发生重复(key不能重复),并且,该类中,所有枚举项的枚举值(value)应是一个常量。
显然,上面的代码不符合这一要求。
那么,我们如何在Python中模拟枚举类型呢?我们可以使用Python中已经提供的enum模块。
from enum import Enum
from enum import Enum
class weather(Enum) {
SUNNY = "sunny"
WINDY = "windy"
RAINY = "rainy"
}
print(weather.SUNNY) # 输出 weather.SUNNY
print(type(weather.SUNNY)) # 输出 <enum 'weather'>
print(weather.SUNNY.name) # 输出 SUNNY
print(weather.SUNNY.value) # 输出 sunny
— END