代码之家  ›  专栏  ›  技术社区  ›  ap14

Python-在比较中使用时默认获取枚举值

  •  3
  • ap14  · 技术社区  · 6 年前

    class MsgType(Enum):
        # ADMINISTRATIVE MESSAGE
        HEARTBEAT = "0"
        LOGON = "A"
        LOGOUT = "5"
        REJECT_SESSION_LEVEL = "3"
        RESEND_REQUEST = "2"
        SEQUENCE_RESET = "4"
        SESSION_REJECT = "3"
        TEST_REQUEST = "1"
    

    我想用这个类与我在阅读消息后得到的字符串进行比较。我正在比较如图所示的值。中的值 msg_type 是类型的 str .

    def read_admin_msg(message):
        msg_type = read_header(message)
        if msg_type == ct.MsgType.HEARTBEAT:
            print(msg_type)
        elif msg_type == ct.MsgType.LOGON:
            print(msg_type)
        elif msg_type == ct.MsgType.LOGOUT:
            print(msg_type)
        elif msg_type == ct.MsgType.REJECT_SESSION_LEVEL:
            print(msg_type)
        elif msg_type == ct.MsgType.RESEND_REQUEST:
            print(msg_type)
        elif msg_type == ct.MsgType.SEQUENCE_RESET:
            print(msg_type)
        elif msg_type == ct.MsgType.SESSION_REJECT:
            print(msg_type)
        elif msg_type == ct.MsgType.TEST_REQUEST:
            print(msg_type)
        else:
            print("Not found")
            print(msg_type)
    

    我期待着,因为 msg_type = "A" 声明 msg_type == ct.MsgType.LOGON 应该是 True else 语句被执行。

    如果我写 ct.MsgType.LOGON.value 然后我得到了想要的结果。但是我希望这个行为是类的默认行为。我应该重写哪个方法,还是应该尝试其他方法?

    2 回复  |  直到 6 年前
        1
  •  4
  •   wholevinski    6 年前

    msg_type = "A" 价值 枚举的。你需要改变你平等比较的一面。或者:

    elif msg_type == MsgType.LOGON.value:
        print(msg_type)
    

    # This one is probably preferred
    elif MsgType(msg_type) == MsgType.LOGON:
        print(msg_type)
    

    编辑:我看到你关于使用 .value 现在。如果你想覆盖 __eq__ 在你的 MsgType 同学们,你们可以。但你会打破默认的平等比较 Enums 在这个过程中,你必须有一个特殊的类型检查在那里检查你的左/右侧是否是一个字符串/枚举/等等 read_header 函数返回枚举的实例,而不是字符串值。

        2
  •  2
  •   Ethan Furman    5 年前

    这里的关键问题是如果 msg_type 无效。例如,可能是因为一个错误或损坏 msg_type == 'z'

    如果一个异常是合适的,那么最简单的方法就是使用

    msg_type = MsgType(msg_type)
    

    这将产生一个 ValueError 对于非法值,您可以立即进行处理:

    try:
        msg_type = MsgType(msg_type)
        # your if...elif...else here
    except ValueError:
        # handle problem here
    

    或者让它上升到一个更高的函数。

    MsgType.LOGON.value 就是让 MsgType Enum 派生自 str

    class MsgType(str, Enum):
        # definitions here
    

    然后在代码中可以说:

    if msg_type == 'A':
        # stuff
    

    不转换 消息类型 .

    我的偏好是第一种方法(不要混用) str公司 ,并执行转换),除非要添加 现有的代码库和 LOGON , HEARTBEAT 等是常量,已在其他地方使用。

    请注意,即使使用第二种方法,您仍然可以使用 MsgType(msg_type) 值错误 例外情况,如果你需要的话。