Python: Enum枚举的实现
本文内容纲要:
从C系语言过来用Python,好不容易适应了写代码不打花括号,突然有一天发现它居然木有枚举……于是stackoverflow了一把,发现神人的枚举(enum)实现到处都是,于是汉化总结过来。
如果是新版Python用户(Python3.4withPEP435):
fromenumimportEnum
Animal=Enum('Animal','antbeecatdog')
or
classAnimals(Enum):
ant=1
bee=2
cat=3
dog=4
旧版Python用户可以充分发挥动态语言的优越性来构造枚举,有简单的:
defenum(**enums):
returntype('Enum',(),enums)
Numbers=enum(ONE=1,TWO=2,THREE='three')
#Numbers.ONE==1,Numbers.TWO==2andNumbers.THREE=='three'
有复杂的:
defenum(*sequential,**named):
enums=dict(zip(sequential,range(len(sequential))),**named)
returntype('Enum',(),enums)
Numbers=enum('ZERO','ONE','TWO')
#Numbers.ZERO==0andNumbers.ONE==1
有带值到名称映射的:
defenum(*sequential,**named):
enums=dict(zip(sequential,range(len(sequential))),**named)
reverse=dict((value,key)forkey,valueinenums.iteritems())
enums['reverse_mapping']=reverse
returntype('Enum',(),enums)
#Numbers.reverse_mapping['three']=='THREE'
有用set实现的:
classEnum(set):
def__getattr__(self,name):
ifnameinself:
returnname
raiseAttributeError
Animals=Enum(["DOG","CAT","HORSE"])
printAnimals.DOG
有用range实现的:
dog,cat,rabbit=range(3)
#or
classStationary:
(Pen,Pencil,Eraser)=range(0,3)
printStationary.Pen
有用tuple实现的:
classEnum(tuple):__getattr__=tuple.index
State=Enum(['Unclaimed','Claimed'])
printState.Claimed
有用namedtuple实现的:
fromcollectionsimportnamedtuple
defenum(*keys):
returnnamedtuple('Enum',keys)(*keys)
MyEnum=enum('FOO','BAR','BAZ')
#带字符数字映射的,像C/C++
defenum(*keys):
returnnamedtuple('Enum',keys)(*range(len(keys)))
#带字典映射的,可以映射出各种类型,不局限于数字
defenum(**kwargs):
returnnamedtuple('Enum',kwargs.keys())(*kwargs.values())
本文内容总结:
原文链接:https://www.cnblogs.com/codingmylife/archive/2013/05/31/3110656.html