Python 模拟enum枚举类型
本文主要介绍Python中模拟enum枚举类型的5种方法,简单实用
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']
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2015-02-01 00:35:39
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: Python 模拟enum枚举类型 (米扑博客)