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

yipeiwu_com5年前Python基础

以下几种方法来模拟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编程实现的图片识别功能示例

本文实例讲述了Python编程实现的图片识别功能。分享给大家供大家参考,具体如下: 1. 安装PIL,官方没有WIN64位,Pillow替代 pip install Pillow-2.7...

Python打开文件,将list、numpy数组内容写入txt文件中的方法

python保存numpy数据: numpy.savetxt("result.txt", numpy_data); 保存list数据: file=open('data.txt'...

弄懂这56个Python使用技巧(轻松掌握Python高效开发)

1. 枚举 - enumerate 可以有参数哦 之前我们这样操作: i = 0for item in iterable: print i, item i += 1 现在我们这...

python聊天程序实例代码分享

代码简单,直接看代码吧:复制代码 代码如下:import socketimport threadingimport re#import Tkinter def ser(): &...

python进程的状态、创建及使用方法详解

本文实例讲述了python进程的状态、创建及使用方法。分享给大家供大家参考,具体如下: 进程以及状态 1. 进程 程序:例如xxx.py这是程序,是一个静态的 进程:一个程序运行起来后,...