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/

相关文章:

ios - 如何使枚举符合 Swift 中的可识别协议(protocol)?

python - 机器学习中测试集需要数据清理吗?

python - E : Unable to find a source package for psycopg2 or use pip with virtualenv

python - websocket 运行异步函数但返回错误 : asyncio. run() 无法从正在运行的事件循环调用

python - Python 中仅当所有 try 语句都成功时才运行语句

Python asyncio 缓冲和处理数据

python - 在 Python 中设置正确的 Tkinter 小部件位置

python - 函数 open() 在 Visual Studio Code 中不起作用

java - 以不同的方式将枚举映射到 Spring 形式选择

Java:创建预定义颜色的数组