python枚举之Enum模块

枚举是与多个唯一常量值绑定的一组符号(即成员)。枚举中的成员可以进行身份比较,并且枚举自身也可迭代。
枚举成员名称建议使用大写字母
# 示例
from enum import Enum,unique, IntEnum(支持成员比较)
@unique   # unique装饰器确保属性名和值唯一
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    # YELLOW = 2  会报错


// 不以类形式构造枚举
BugStatus = enum.Enum(
  value='BugStatus',
  names=[
    ('new', 3)
    ('old', 2)
    ('won_fix', 1)
  ],
)
for status in BugStatus:
  print("{0}:{1}".format(status.name, status.value))


// 非整数成员值,元组
import enum
class BugStatus(enum.Enum):
    new = (7, ['incomplete', 'invalid', 'won_fix', 'in_progress'])
    incomplete = (6, ['new', 'wond_fix'])
    invalid = (5, ['new'])
    wont_fix = (4, ['new'])
    in_progress = (3, ['new', 'fix_committed'])
    fix_committed = (2, ['in_progress', 'fix_released'])
    fix_released = (1, ['new'])

    def __init__(self, num: int, transitions: list) -> None:
        self.num = num
        self.transitions = transitions

    def can_transition(self, new_state: object):
        print(new_state.name)
        print(self.transitions)
        return new_state.name in self.transitions

# 如果成员的值是一个元组,那么成员会被作为单个参数被传递到__init__()
print('Name', BugStatus.in_progress)
print('Value', BugStatus.in_progress.value) # (3, ['new', 'fix_committed'])
print('Custom attribute:', BugStatus.in_progress.transitions) #  ['new', 'fix_committed']
print('Using attribute:', BugStatus.in_progress.can_transition(BugStatus.new))  #True

# 使用字典
import enum


class BugStatus(enum.Enum):

    new = {
        'num': 7,
        'transitions': [
            'incomplete',
            'invalid',
            'wont_fix',
            'in_progress',
        ],
    }
    incomplete = {'num': 6, 'transitions': ['new']}

    # 复杂成员的值会被作为唯一参数传递__init__()
    def __init__(self, vals: dict) -> None:
        self.num = vals['num']
        self.transitions = vals['transitions']

    def can_transition(self, new_state: object):
        return new_state.name in self.transitions
posted @ 2021-11-22 15:50  我在路上回头看  阅读(257)  评论(0编辑  收藏  举报