>>> 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 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