python - 从枚举类获取值,其中枚举成员名称在 Python 中运行时已知

标签 python python-3.x enums

我试图通过获取枚举成员名称 runtime 从枚举类中获取枚举值。我正在尝试以下方式:

from enum import Enum


    class EnumList(Enum):

        foo = 1
        bar = 2
enumMemberName=input("Enter enum member name")
enumValue=repr(EnumList.enumMemberName)          // **AttributeError: enumMemberName**
enumValue=repr(EnumList.foo)                     // **working fine**

请提供上述问题的替代解决方案。

最佳答案

我想这就是你想要的:

edit:根据 OP 反馈修改答案。

from enum import Enum


class EnumList(Enum):

    foo = 1
    bar = 2


enumMemberName=input("Enter enum member name")

enumMember = EnumList.foo
enumMemberTwo = EnumList[enumMemberName]

enumValue = EnumList[enumMemberName].value
enumValueStr = repr(EnumList[enumMemberName].value)

引自documentation for Enum

From Enum documentation

关于python - 从枚举类获取值,其中枚举成员名称在 Python 中运行时已知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59100315/

相关文章:

python - 结合 shell 和 python 代码

python - 将长数字文字分成多行

django - 如何在 Python 模型迁移中生成基于函数的索引?

swift - 调整自定义类以与 CoreData 兼容

java - 如何使用枚举在数组列表中设置优先级?

python - Google App Script API 无法验证 "Request contains an invalid argument"

python - 如何使用pytest模拟类属性

python - 无法使用通用模数攻击解码 RSA 消息?

c# - 枚举函数错误

python - 来自 HTML 表中相同表单类的多个 WTForm 字段?