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

yipeiwu_com6年前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编写一个闹钟功能

音频文件放入和.py文件同级的目录下 import winsound # 导入此模块实现声音播放功能 import time # 导入此模块,获取当前时间 # 提示用户设置时间和分钟...

Python对数据进行插值和下采样的方法

使用Python进行插值非常方便,可以直接使用scipy中的interpolate import numpy as np x1 = np.linspace(1, 4096, 1024...

详解设计模式中的工厂方法模式在Python程序中的运用

详解设计模式中的工厂方法模式在Python程序中的运用

工厂方法(Factory Method)模式又称为虚拟构造器(Virtual Constructor)模式或者多态工厂(Polymorphic Factory)模式,属于类的创建型模式。...

Python中常见的异常总结

一、异常错误    a、语法错误 错误一: if 错误二: def  text:       pass...

pandas删除指定行详解

pandas删除指定行详解

在处理pandas的DataFrame中,如果想像excel那样筛选,只要其中的某一行或者几行,可以使用isin()方法来实现,只需要将需要的行值以列表方式传入即可,还可传入字典,进行指...