具有复杂类型的Python枚举

马赛尔·格森尼(Marcell Gerzsenyi)

我有枚举类型:

 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值的enum变量:

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

我当然很高兴:

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

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

阿里·戈尔德(Ari Gold)
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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章