Python: Enum枚举的实现
如果是新版Python用户(Python 3.4 with PEP 435):
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog') 或者:
class Animals(Enum):
ant = 1
bee = 2
cat = 3
dog = 4
旧版的python实现:
def enum(**enums):
return type('Enum', (), enums)
Numbers = enum(ONE=1, TWO=2, THREE='three')
# Numbers.ONE == 1, Numbers.TWO == 2 and Numbers.THREE == 'three'
本文介绍在新版及旧版Python中实现枚举的方法。新版Python可通过`Enum`模块定义枚举类,旧版Python则通过自定义类型实现。适用于Python3.4及以上版本。
194

被折叠的 条评论
为什么被折叠?



