Python中模拟enum枚举类型的5种方法分享
以下几种方法来模拟enum:(感觉方法一简单实用)
代码如下:
# way1 class Directions: up = 0 down = 1 left = 2 right =3 print Directions.down # way2 dirUp, dirDown, dirLeft, dirRight = range(4) print dirDown # way3 import collections dircoll=collections.namedtuple('directions', ('UP', 'DOWN', 'LEFT', 'RIGHT')) directions=dircoll(0,1,2,3) print directions.DOWN # way4 def enum(args, start=0): class Enum(object): __slots__ = args.split() def __init__(self): for i, key in enumerate(Enum.__slots__, start): setattr(self, key, i) return Enum() e_dir = enum('up down left right') print e_dir.down # way5 # some times we need use enum value as string Directions = {'up':'up','down':'down','left':'left', 'right':'right'} print Directions['down']
相关推荐
NoBlueSky 2019-11-17
taizuduojie 2019-11-03
liangds 2019-08-02
paopao00 2019-06-29
hhboyggyy 2010-04-26
尘封飞扬 2009-04-14
举 2019-04-02
ObjectiveC 2016-09-25
shangs00 2010-02-03
PythonGCS 2015-04-30
Airuio 2020-02-12
AlexZhao 2019-11-09
zhglinux 2019-06-29
囧芝麻 2013-08-22
jerry00 2019-06-28
surpassdream 2012-11-03
rosekissyou 2010-12-28