python模拟enum枚举类型的方法小结
本文实例总结了python模拟enum枚举类型的方法。分享给大家供大家参考。具体分析如下:
python中没有enum枚举类型,可能python认为这玩意压根就没用,下面列举了三种方法模拟enum枚举类型
方法1. 使用自定义类
class Numbers(object): ONE = 1 TWO = 2 THREE = 3 assert Numbers.ONE == 1 assert Numbers.TWO == 2 assert Numbers.THREE == 3
方法2:使用函数动态创建类
def enum(**enums): return type('Enum', (object,), enums) Numbers = enum(ONE=1, TWO=2, THREE=3) assert Numbers.ONE == 1 assert Numbers.TWO == 2 assert Numbers.THREE == 3
方法3:创建一个从python的集合扩展来的对象
class Enum(set): def __getattr__(self, name): if name in self: return name raise AttributeError Numbers = Enum( "ONE TWO THREE".split() ) error = False try: print Numbers.ONE print Numbers.TWO print Numbers.THREE except: error = True assert error == False try: print Numbers.FOUR except: error = True assert error == True
希望本文所述对大家的python程序设计有所帮助。
相关推荐
拉斯厄尔高福 2020-10-19
83540690 2020-08-16
lustdevil 2020-08-03
doupoo 2020-07-28
yuzhongdelei0 2020-07-04
lustdevil 2020-06-25
lustdevil 2020-06-21
上班打发 2020-06-14
xcguoyu 2020-05-15
fanhuasijin 2020-02-17
sulindong0 2020-02-15
Julywhj 2020-02-02
xiaobater 2020-02-02
柠檬班 2020-01-30
KilluaZoldyck 2020-01-29
JackYin 2020-01-24
86427019 2020-01-20
taoqilin 2020-01-18
八角塘塘主 2020-01-04