您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python中模拟enum枚举类型的5种方法分享

2025/11/2 18:33:05发布27次查看
以下几种方法来模拟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']
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product