Python中模拟enum枚举类型的5种方法分享
程序员文章站
2023-11-02 23:57:15
以下几种方法来模拟enum:(感觉方法一简单实用)
复制代码 代码如下:
# way1
class directions:
u...
以下几种方法来模拟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']
上一篇: 站长赚钱方法解析:以用户为中心