简体   繁体   English

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

[英]Python Enum: How to get enum values with multiple attributes

I have defined two enums with attributes.我已经定义了两个带有属性的枚举。 When I want to access an enum element by specifying its attribute it works for enum A (one attribute) but not for enum B (two attributes):当我想通过指定其属性来访问枚举元素时,它适用于枚举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'))

I get the following output:我得到以下输出:

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

What am I missing here?我在这里想念什么?

The correct syntax is B(('Val', 'One')) , passing the value of the enum directly (thus in this case a tuple), or simply naming the enum variant by name: B.ValOne .正确的语法是B(('Val', 'One')) ,直接传递枚举的值(因此在这种情况下是一个元组),或者简单地按名称命名枚举变量: B.ValOne

I must admit this is confusing, with __init__ automagically destructuring the tuple into two arguments.我必须承认这是令人困惑的,因为__init__自动将元组解构为两个参数。 The error isn't helpful either.该错误也没有帮助。

The biggest thing you missing is that ('One') is not a tuple -- you need a comma ( , ), which would look like ('One', ) .你最想念的是('One')不是一个tuple ——你需要一个逗号 ( , ),它看起来像('One', )

So A is made of single, non-tuple, values 'One' and 'Two' .所以A由单个非元组值'One''Two'组成。

B , however, is made of tuples, but然而, B是由元组组成的,但是

 B('Val', 'One')

is not passing a tuple to B , it is passing two arguments: 'Val' and 'One' .不是将tuple传递给B ,而是传递两个参数: 'Val''One' As @orlp mentioned, passing a tuple using function syntax looks like:正如@orlp 提到的,使用函数语法传递一个元组看起来像:

B(('Val', 'One'))

Finally, in the definitions of A 's and B 's members, you do not need the parentheses:最后,在AB成员的定义中,您不需要括号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM