Python中模拟enum枚举类型的5种方法分享
以下几种方法来模拟enum:(感觉方法一简单实用)
#way1 classDirections: up=0 down=1 left=2 right=3 printDirections.down
#way2 dirUp,dirDown,dirLeft,dirRight=range(4)
printdirDown
#way3 importcollections dircoll=collections.namedtuple('directions',('UP','DOWN','LEFT','RIGHT')) directions=dircoll(0,1,2,3)
printdirections.DOWN
#way4 defenum(args,start=0): classEnum(object): __slots__=args.split()
def__init__(self): fori,keyinenumerate(Enum.__slots__,start): setattr(self,key,i)
returnEnum()
e_dir=enum('updownleftright')
printe_dir.down
#way5 #sometimesweneeduseenumvalueasstring Directions={'up':'up','down':'down','left':'left','right':'right'}