Python Enum 枚举 用法汇总

Python Enum 枚举 用法汇总

import os
import sys
if sys.version_info.major + sys.version_info.minor * 0.1 < 3.4:
    from enum34 import Enum
else:
    from enum import Enum

class MyColorEnum(Enum):
    red = 1
    red_alias = 1
    blue = 2
    green = 'green'

MyColorEnum.red.name    # get member name string
MyColorEnum.red.value   # get member value

for c in MyColorEnum:
    print(c)    # just one of MyColorEnum.red_alias and MyColorEnum.red, according to the order which itself decides

for c in MyColorEnum.__members__.items():
    c[0]    # str name eg. 'red'
    c[1]    # member eg. MyColorEnum.red
    # contain 'red_alias' and MyColorEnum.red_alias

'red' in MyColorEnum.__members__    # if member name in Enum
0 in MyColorEnum._value2member_map_ # if value in Enum values

MyColorEnum.__members__['red']  # MyColorEnum.red, get member by member name string, if no such member name string, raising KeyError

# comparation ################################################################################
MyColorEnum.red is MyColorEnum.red_alias    # True
MyColorEnum.red == MyColorEnum.red_alias    # True
MyColorEnum.red != MyColorEnum.red_alias    # False
isinstance(None, MyColorEnum)  # False
isinstance(MyColorEnum.red, MyColorEnum) # True
#never do this
#MyColorEnum.red < MyColorEnum.blue  # raising TypeError, Enum values could be different types

 IntEnum:支持排序,value只能是int

from enum import  IntEnum
class IntColorEnum(IntEnum):
    red = 0
    yellow = 1
    green = 3
sorted([IntColorEnum.green, IntColorEnum.red])

 以下是在Enum中定义方法:

class Color(Enum):
    red = 1
    
    def fun(self):
        return self.value

    @classmethod
    def fun2(cls):
        return cls.red

Color.fun2()
Color.red.fun()

 

posted @ 2019-02-14 17:08  ibingshan  阅读(4297)  评论(0编辑  收藏  举报