Last active
January 3, 2016 05:19
-
-
Save Arbow/8414639 to your computer and use it in GitHub Desktop.
python enum implement in 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def enum(*sequential, **named): | |
""" 创建自定义枚举类型,支持两种用法: | |
1. enum('Success', 'Failed') | |
会从0开始给Success,Failed分配0,1两个值 | |
2. enum(on=1, off=0) | |
指定on,off两个枚举的值 | |
创建枚举类之后,可以通过调用 set_alias 方法设置枚举值对应的别名, 然后通过 get_alias 获取某个枚举值对应的别名 | |
""" | |
enums = dict(zip(sequential, range(len(sequential))), **named) | |
reverse = dict((value, key) for key, value in enums.iteritems()) | |
enums['reverse_mapping'] = reverse | |
@classmethod | |
def set_alias_func(clz, **alias): | |
setattr(clz, '__alias', dict(map(lambda p:(getattr(clz,p[0]),p[1]), alias.iteritems()))) | |
enums['set_alias'] = set_alias_func | |
@classmethod | |
def get_alias_func(clz, key): | |
return getattr(clz, '__alias')[key] | |
enums['get_alias'] = get_alias_func | |
return type('Enum', (object,), enums) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment