英文:
Can I get both an enum value and enum class name from a string in Python?
问题
可以将这些字符串直接转换为 FooEnum.bar
吗?
英文:
Let's say I have the following Python enum class:
class FooEnum(IntEnum):
foo = auto()
bar = auto()
baz = auto()
And I also have the strings "FooEnum"
and "bar"
. Both of the strings come from HTML select values, which are limited to basic types.
Can I turn these strings directly into a FooEnum.bar
?
答案1
得分: 0
代码部分已经被排除,以下是翻译好的部分:
"enumDict["FooEnum"]["bar"]" 给出 "FooEnum.bar"。
回顾起来,我想不出任何情况下我不知道我的所有类名称,所以很难想象字典不是一个合理的解决方案。
英文:
The common response here suggests that if I want to get a class name from a string, I should be using another data structure like a dictionary.
from enum import IntEnum, auto
class FooEnum(IntEnum):
foo = auto()
bar = auto()
baz = auto()
class SpamEnum(IntEnum):
spam = auto()
eggs = auto()
enumDict = {
"FooEnum": FooEnum,
"SpamEnum": SpamEnum
}
With the above code, enumDict["FooEnum"]["bar"]
gives FooEnum.bar
.
In retrospect, there is no situation I can think of where I wouldn't know all of my class names, so it's hard to imagine a dictionary not being a reasonable solution.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论