我已多次看到这种模式:
>>> 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
如果您正在寻找更健壮的东西(稀疏值,枚举特殊异常等),请尝试此配方.
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 Foo(object): bar = 0 baz = 1 quux = 2 >>> Foo.quux 2
如果您正在寻找更健壮的东西(稀疏值,枚举特殊异常等),请尝试此配方.
我不知道为什么Enums不支持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