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

查看:106
本文介绍了如何扩展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-subclassing-of-枚举

所以,不是直接可能。

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

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