>>> 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
我见过这种模式好几次:
您也可以只使用类成员,但您必须提供自己的编号:
如果您正在寻找更健壮的对象(稀疏值、特定于枚举的异常等),try this recipe。
我不知道为什么Python不支持枚举。 我发现模拟它们的最佳方法是重写str和eq,以便进行比较,当使用print()时,将得到字符串而不是数值。
用法:
相关问题 更多 >
编程相关推荐