如何使用 python 中的输入访问枚举成员

How can I access an enum member with an input in python

我正在尝试使用输入访问 enum 变量的值。

这是我的代码:

class Animals(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 

Choose = input('Choose an animal')

print(Animals.Choose.value)

这可能给我一个错误,因为 Animals 不包含 Choose

如何区分 enum 中的成员和我的输入变量?

所以如果我输入 Dog 它会给出 1Dog 变量的值)?

您可以尝试使用 getattr:

from enum import Enum
class Animals(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 


Choose = input('Choose an animal')

print(getattr(Animals, Choose).value)

输出:

1

getattr代表“获取属性”,这意味着它获取class中的变量,它的名字就是第二个参数。

Enums已经内置了__getitem__方法,所以你可以直接用[]括号索引它,像这样:

print(Animals[Choose].value)

输出:

1

枚举具有内置的字符串访问和多种访问结果的方式。有关详细信息,请参阅 Enum 的文档:

from enum import Enum

class Animal(Enum):
    Dog = 1
    Cat = 2
    Cow = 3 

choice = input('Choose an animal: ')

print(Animal[choice])
print(repr(Animal[choice]))
print(Animal[choice].value)
Choose an animal: Cat
Animal.Cat
<Animal.Cat: 2>
2