• 技术文章 >Python技术 >Python基础教程

    python使用enum进行枚举的比较

    小妮浅浅小妮浅浅2021-06-05 09:56:45原创2876

    1、说明

    (1)枚举成员未被排序,因此它们仅支持通过 is 和 == 进行比较。大小比较引发 TypeError 异常。

    (2)继承 IntEnum 类创建的枚举类,成员间支持大小比较。

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    import enum

      

      

    class BugStatus(enum.Enum):

      

        new = 7

        incomplete = 6

        invalid = 5

        wont_fix = 4

        in_progress = 3

        fix_committed = 2

        fix_released = 1

      

      

    actual_state = BugStatus.wont_fix

    desired_state = BugStatus.fix_released

      

    print('Equality:',

          actual_state == desired_state,

          actual_state == BugStatus.wont_fix)

    print('Identity:',

          actual_state is desired_state,

          actual_state is BugStatus.wont_fix)

    print('Ordered by value:')

    try:

        print('\n'.join('  ' + s.name for s in sorted(BugStatus)))

    except TypeError as err:

        print('  Cannot sort: {}'.format(err))

         

    # output

    # Equality: False True

    # Identity: False True

    # Ordered by value:

    #   Cannot sort: '<' not supported between instances of 'BugStatus' and 'BugStatus'

    以上就是python使用enum进行枚举比较的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python enum
    上一篇:python迭代器如何转换为生成器 下一篇:python Package如何设置文件入口

    相关文章推荐

    • 如何用enumerate在python中统计文本?• python中enumerate函数是什么?• python的enumerate函数有何用法?• java enum使用方法有几种

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网