使用具有重复值的枚举初始化变量

2024-10-02 14:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个具有重复值的枚举类。示例中的每个值以位表示寄存器大小。我想用枚举名初始化变量。因为它们有相同的值,看起来Python第一次出现,忽略了我传递的枚举名

from enum import Enum
class OperandType(Enum):
    EAX = 32
    EBX = 32
   
ebx = 'EBX'
new_op = OperandType[ebx]
print(new_op)

将在此处打印的内容是:

OperandType.EAX

如何让它像我期望的那样工作


Tags: fromimport示例内容newenum寄存器class
2条回答

这也会起作用,因为类实例/枚举值是唯一的:

class OperandSize:
    def __init__(self, size):
    self._operand_size = size

class OperandType(Enum):
    EAX = OperandSize(32)
    AAA = OperandSize(32)

根据the docs

An enumeration is a set of symbolic names (members) bound to unique, constant values.

因此,指向相同值的名称将被视为彼此的别名。另见https://docs.python.org/3.9/library/enum.html#duplicating-enum-members-and-values

Given two members A and B with the same value (and A defined first), B is an alias to A. By-value lookup of the value of A and B will return A. By-name lookup of B will also return A.

在您的例子中,EAX是首先定义的,并且具有与EBX相同的值,因此EBX的查找提供了EAX

至于如何让它像您期望的那样工作:不可能,因为enum不会像这样工作

当然,您可以创建如下映射:

SIZES = {OperandType.EAX: 32, OperandType.EBX: 32}

…然后通过SIZES[OperandType.EAX]查询大小

相关问题 更多 >