Python枚举

2018-07-21  本文已影响0人  人生苦短啊
1. 枚举类型、枚举名称与枚举值

枚举优点: 不可更改性, 不可重复性

from enum import Enum

class Vip(Enum):
    YELLOW = 1
    GREEN = 2
    RED = 3

print(type(Vip.YELLOW.value))       # 枚举值            <class 'int'>
print(type(Vip.YELLOW.name))        # 枚举名字          <class 'str'>
print(type(Vip['RED']))            # 枚举类型          <enum 'Vip'>

for v in Vip:
    print(v.name)       # 遍历枚举
2. 枚举比较

枚举只能进行等于比较不能进行大小比较

from enum import Enum

class Vip(Enum):
    YELLOW = 1
    GREEN = 1
    RED = 3

class Vip2(Enum):
    YELLOW = 1

result = Vip.YELLOW == Vip.GREEN        # True
result = Vip.YELLOW is Vip.GREEN        # True
result1 = Vip.YELLOW == 1               # False
result1 = Vip.YELLOW == Vip2.YELLOW     # False
print(result1)
3. 枚举的别名
from enum import Enum

class Vip(Enum):
    YELLOW = 1
    YELLOW_CHILD = 1                # 两个枚举值相同, 第二个值系统会把它当做别名, 遍历的时候不会显示
    RED = 3

for v in Vip:
    print(v)            # Vip.YELLOW
                        # Vip.RED

for v in Vip.__members__:          # __members__会把别名也返回
    print(v)                        # YELLOW
                                    # YELLOW_CHILD
                                    # RED
4. IntEnum,unique
from enum import IntEnum,unique

# InfEnum 会控制枚举里面都是int类型,如果不是就会报错,
# unique 会控制枚举各个值是唯一的
@unique
class Vip(IntEnum):
    YELLOW = 1
    YELLOW_CHILD = 1          # 报错
    RED = 3

print(Vip.YELLOW)
上一篇 下一篇

猜你喜欢

热点阅读