python - 在 Python 中动态创建具有自定义值的枚举?

标签 python enums

我想通过读取 YAML 文件中的值在运行时创建枚举类型。所以我有这个:

# Fetch the values
v = {'foo':42, 'bar':24}

# Create the enum
e = type('Enum', (), v)

有正确的方法吗?我感觉在呼唤type这不是一个非常简洁的解决方案。

最佳答案

您可以使用 Enum functional API 创建新的枚举类型:

In [1]: import enum

In [2]: DynamicEnum = enum.Enum('DynamicEnum', {'foo':42, 'bar':24})

In [3]: type(DynamicEnum)
Out[3]: enum.EnumMeta

In [4]: DynamicEnum.foo
Out[4]: <DynamicEnum.foo: 42>

In [5]: DynamicEnum.bar
Out[5]: <DynamicEnum.bar: 24>

In [6]: list(DynamicEnum)
Out[6]: [<DynamicEnum.foo: 42>, <DynamicEnum.bar: 24>]

关于python - 在 Python 中动态创建具有自定义值的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690064/

相关文章:

python - elisp 相当于 python shlex.split?

python - PyOpenSSL 引发加载证书错误

c - 结构数组 : Structure members are Enum Variables

c# - 为什么不能通过表达式引用类型?

python - 在 Tensorflow 中使用初始模型进行迁移学习(python)

python - 使用 Python 从 json API 响应中提取属性

python - Google App Engine Search API 执行基于位置的搜索

c# - Unity - 使用枚举属性来检测对象碰撞

java - 使用反射动态调用正确的正确设置方法

swift - 我可以将枚举定义为另一个枚举案例的子集吗?