码迷,mamicode.com
首页 > 编程语言 > 详细

python技巧31[python中使用enum][转]

时间:2015-02-23 11:57:03      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

以下几种方法来模拟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

        http://www.cnblogs.com/itech/archive/2011/03/08/1977245.html

python技巧31[python中使用enum][转]

标签:

原文地址:http://www.cnblogs.com/sunshine-anycall/p/4297925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!