在Python中,我可以从字符串中获取枚举值和枚举类名吗?

huangapple go评论99阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月14日 06:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75441624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定