Python Enum:如何获取具有多个属性的枚举值

Mar*_*kuz 2 python enums

我定义了两个带有属性的枚举。当我想通过指定属性来访问枚举元素时,它适用于枚举A(一个属性),但不适用于枚举B(两个属性):

from enum import Enum

class A(Enum):
    ValOne = ('One')
    ValTwo = ('Two')

    def __init__(self, num):
        self.num = num

class B(Enum):
    ValOne = ('Val', 'One')
    ValTwo = ('Val', 'Two')

    def __init__(self, val, num):
        self.val = val
        self.num = num

print(A('One'))
print(B('Val', 'One'))
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

A.ValOne
Traceback (most recent call last):
  File "test.py", line 19, in <module>
    print(B('Val', 'One'))
  File "/usr/lib/python3.8/enum.py", line 341, in __call__
    return cls._create_(
  File "/usr/lib/python3.8/enum.py", line 444, in _create_
    _, first_enum = cls._get_mixins_(cls, bases)
  File "/usr/lib/python3.8/enum.py", line 576, in _get_mixins_
    raise TypeError("Cannot extend enumerations")
TypeError: Cannot extend enumerations
Run Code Online (Sandbox Code Playgroud)

我在这里缺少什么?

Eth*_*man 8

更新

在 Python 3.12 中,按值查找的有效签名是:

B(*values)
Run Code Online (Sandbox Code Playgroud)

所以

B('Val', 'One')
Run Code Online (Sandbox Code Playgroud)

将按预期工作并返回

<B.ValOne: ('Val', 'One')>
Run Code Online (Sandbox Code Playgroud)

尽管

B(('Val', 'One'))
Run Code Online (Sandbox Code Playgroud)

将继续正常工作。


您缺少的最重要的事情是,这('One')不是tuple- 您需要一个逗号 ( ,),它看起来像('One', )

SoA由单个、非元组、值'One'和组成'Two'

B,然而,是由元组组成的,但是

 B('Val', 'One')
Run Code Online (Sandbox Code Playgroud)

不是传递 a tupleto B,而是传递两个参数:'Val''One'。正如 @orlp 提到的,使用函数语法传递元组如下所示:

B(('Val', 'One'))
Run Code Online (Sandbox Code Playgroud)

A最后,在s 和s 成员的定义中B,不需要括号:

class A(Enum):
    ValOne = 'One'
    ValTwo = 'Two'

    def __init__(self, num):
        self.num = num


class B(Enum):
    ValOne = 'Val', 'One'
    ValTwo = 'Val', 'Two'

    def __init__(self, val, num):
        self.val = val
        self.num = num
Run Code Online (Sandbox Code Playgroud)

声明:我是Python stdlibEnumenum34backportAdvanced Enumeration ( aenum)库的作者 。