我该如何在Python中实现一个枚举类型(在一些编程语言中拼写为enum
)?获取此功能的常见做法是什么?
class Materials:
Shaded, Shiny, Transparent, Matte = range(4)
>>> print Materials.Matte
3
从 Python 3.4+ 开始,你可以使用 enum 模块中的 Enum
(或者带有 int
值的枚举类型可以用 IntEnum
)来定义枚举类型。使用 enum.auto
可以自动递增枚举值:
import enum
class Materials(enum.IntEnum):
Shaded = 1
Shiny = enum.auto()
Transparent = 3
Matte = enum.auto()
print(Materials.Shiny == 2) # True
print(Materials.Matte == 4) # True
我已经多次看到这个模式:
>>> class Enumeration(object):
def __init__(self, names): # or *names, with no .split()
for number, name in enumerate(names.split()):
setattr(self, name, number)
>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2
您也可以直接使用类成员,不过您需要自己提供编号:
>>> class Foo(object):
bar = 0
baz = 1
quux = 2
>>> Foo.quux
2
如果你正在寻找更为强大的功能(支持稀疏值、特定枚举类型的异常等),可以尝试这个代码示例。
我不知道为什么 Python 没有原生支持枚举类型。我找到的最好的模拟方法是通过覆盖 _ str _ 和 _ eq _ 来实现,这样你可以比较它们,在使用 print() 时可以获得字符串而不是数值。
class enumSeason():
Spring = 0
Summer = 1
Fall = 2
Winter = 3
def __init__(self, Type):
self.value = Type
def __str__(self):
if self.value == enumSeason.Spring:
return 'Spring'
if self.value == enumSeason.Summer:
return 'Summer'
if self.value == enumSeason.Fall:
return 'Fall'
if self.value == enumSeason.Winter:
return 'Winter'
def __eq__(self,y):
return self.value==y.value
用法:
>>> s = enumSeason(enumSeason.Spring)
>>> print(s)
Spring
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy