python技巧31[python中使用enum]
2013-03-24 19:31
399 查看
以下几种方法来模拟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']
问题:有的时候需要使用enum的值作为字符串使用,像way5中表示的,大家有没有更好的办法?
参考:http://audbel.com/0/5009691
完!
# 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']
问题:有的时候需要使用enum的值作为字符串使用,像way5中表示的,大家有没有更好的办法?
参考:http://audbel.com/0/5009691
完!
相关文章推荐
- python技巧31[python中使用enum](转)
- python技巧31[python中使用enum]
- python技巧31[python中使用enum]
- python技巧31[python中使用enum][转]
- python常见使用技巧
- python的IDE之spyder快捷键和使用技巧
- python技巧31[对象相等性|dictionary模拟switchcase]
- python高效编程技巧14(如何使用线程池)
- 1.2.4 在Python中使用向量化的技巧和注意事项
- python技巧31[unicode和bytes]
- python3使用了更多内存优化的技巧,比如,python3的zip就是生成可迭代的对象
- C# Enum设计和使用的相关技巧
- python技巧31[判断操作系统类型]
- python技巧31[pythonTips1]
- Python 使用技巧 常见问题
- Python黑魔法@property装饰器的使用技巧解析
- Python3基础 使用技巧:把代码的字体变大
- C# Enum设计和使用的相关技巧
- python开发工具pycharm之 快捷键 使用技巧
- Python使用技巧(0)