手机
当前位置:查字典教程网 >脚本专栏 >python >Python中模拟enum枚举类型的5种方法分享
Python中模拟enum枚举类型的5种方法分享
摘要:以下几种方法来模拟enum:(感觉方法一简单实用)复制代码代码如下:#way1classDirections:up=0down=1left=...

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

【Python中模拟enum枚举类型的5种方法分享】相关文章:

Python urlopen()函数 示例分享

Python中apply函数的用法实例教程

python的正则表达式re模块的常用方法

python3.3教程之模拟百度登陆代码分享

python中定义结构体的方法

python中的yield使用方法

Python删除指定目录下过期文件的2个脚本分享

Python中的魔法方法深入理解

python使用7z解压软件备份文件脚本分享

python操作MySQL数据库的方法分享

精品推荐
分类导航