如何扩展 Python 枚举? [英] How to extend Python Enum?

查看:23
本文介绍了如何扩展 Python 枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is best practice for extending Enum type in Python 3.4 and is there even a possibility for do this?

例如:

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 枚举的继承?

Currently there is no possible way to create a base enum class with members and use it in other enum classes (like in the example above). Is there any other way to implement inheritance for Python enums?

推荐答案

仅当枚举未定义任何成员时才允许对枚举进行子类化.

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

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

So no, it's not directly possible.

这篇关于如何扩展 Python 枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆