python - 如何扩展 Python 枚举?

标签 python python-3.x enums

在 Python 3.4 中扩展 Enum 类型的最佳实践是什么?甚至有可能这样做吗?

例如:

from enum import Enum

class EventStatus(Enum):
   success = 0
   failure = 1

class BookingStatus(EventStatus):
   duplicate = 2
   unknown = 3

Traceback (most recent call last):
...
TypeError: Cannot extend enumerations

目前没有可能的方法来创建具有成员的基本枚举类并将其用于其他枚举类(如上面的示例中)。有没有其他方法可以实现 Python 枚举的继承?

最佳答案

Subclassing an enumeration is allowed only if the enumeration does not define any members.

Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances.

https://docs.python.org/3/library/enum.html#restricted-enum-subclassing

所以,这不是直接可能的。

关于python - 如何扩展 Python 枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33679930/

相关文章:

python - 安装 Anaconda Python 时出现冲突

python - 绘制的图少于 matplotlib 子图中指定的图

oop - 将Dart枚举放入类或包导出文件中

java - 在枚举类型上实现 `next` 和 `previous` 的最佳方法是什么?

python - 如何构建一个系统来处理 MQTT 代理和 Django

python - 如何使用 Python 清空文件

python - Windows 上带有套接字包装器的 `OSError: [Errno 9] Bad file descriptor`

python-3.x - Python 中 2 到 64 之间的随机数,但只有 2 ** 2

python - 如何使用 Python 3 引用某些列或行

spring-mvc - @RequestParam defaultvalue 不接受枚举值作为默认值