Python中枚举的常用做法是什么?

可能重复:
我怎样才能在Python中表示一个“枚举”?

Python中枚举的常用做法是什么? 即他们如何在Python中复制?

public enum Materials { Shaded, Shiny, Transparent, Matte } 
 class Materials: Shaded, Shiny, Transparent, Matte = range(4) >>> print Materials.Matte 3 

我已经看了几次这个模式:

 >>> 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级成员,但你必须提供你自己的编号:

 >>> class Foo(object): bar = 0 baz = 1 quux = 2 >>> Foo.quux 2 

如果您正在寻找更强大的function(稀疏值,特定于枚举的exception等),请尝试使用此配方 。

你或许可以使用inheritance结构,尽pipe我用这个感觉越来越脏。

 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 

我不知道为什么枚举不是由Python本地支持。 我发现模拟它们的最好方法是覆盖_ str _和_ eq _,以便比较它们,当使用print()时,您将获得string而不是数字值。

 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