具有复杂类型的Python枚举 [英] Python Enum with complex type

查看:47
本文介绍了具有复杂类型的Python枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的枚举类型为:

 class SystemCommands(Enum):
    Get_FW_version = (0, 1)
    Get_MAC_address = (1,1)
    Set_MAC_address = (2,7)
    Get_IP_addr = (3,1)
    Set_IP_addr = (4,5)
    Get_server_IP_addr = (5,1)
    Set_server_IP_addr = (6,5)
    Get_subnet_Mask = (7,1)
    Set_subnet_Mask = (8,5)
    Get_Gateway_Address = (9,1)
    Set_Gateway_Address = (10,5)
    Welcome = (16,1)
    Request_Cannot_Served = (17,1)

    def __init__(self, CommandCode, length):
        self.CommandCode = CommandCode
        self.length = length

我只想基于一个int值创建一个枚举变量:

I would like to create an enum variable based only on an int value:

code =10
...
Request = SystemCommands(code)

我当然很高兴:

 raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 10 is not a valid SystemCommands

问题:如何仅基于一个值创建复杂类型的枚举?

Question: How can I create a complex-typed enum based only one value?

推荐答案

from enum import Enum
class SystemCommands(Enum):
  Get_FW_version = (0, 1)
  Get_MAC_address = (1,1)
  Set_MAC_address = (2,7)
  Get_IP_addr = (3,1)
  Set_IP_addr = (4,5)
  Get_server_IP_addr = (5,1)
  Set_server_IP_addr = (6,5)
  Get_subnet_Mask = (7,1)
  Set_subnet_Mask = (8,5)
  Get_Gateway_Address = (9,1)
  Set_Gateway_Address = (10,5)
  Welcome = (16,1)
  Request_Cannot_Served = (17,1)

  def __init__(self, CommandCode, length):
      self.CommandCode = CommandCode
      self.length = length

# Moses is right but you can also do something like that (workaround)
# use @unique to protect duplicates
code = 10
for val in SystemCommands:
  if val.value[0] == code:
    print (val)

# SystemCommands.Set_Gateway_Address

这篇关于具有复杂类型的Python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆