python使用enum进行枚举的比较

2025-12-01 0 83,335

1、说明

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

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

2、实例

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电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python使用enum进行枚举的比较 https://www.zhiup.top/1866.html

相关