Python枚举组合

我想基于两个现有的类创建一个新的Enum(IntEnum)类.有一个可行的解决方案,如下所示:

from enum import unique, IntEnum
from itertools import chain
from collections import OrderedDict

@unique
class FirstEnumClass(IntEnum):
    a = 1
    b = 2

@unique
class SecondEnumClass(IntEnum):
    c = 3
    d = 4

# here a combined class is created:
CombinedEnumClass = unique(IntEnum('CombinedEnumClass', OrderedDict([(i.name, i.value) for i in chain(FirstEnumClass, SecondEnumClass)])))

我的问题:是否有一种理想的方法来实现这一点,以便有一个正确的类定义?像重写某些元类方法一样?我想要这样的东西,所以也可以给出docstring:

@unique
class CombinedEnumClass(IntEnum):
    """ docstring """
    # magic needed here

任何想法?谢谢!

解决方法:

prevents explicitly库可以做到这一点:

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. On the
other hand, it makes sense to allow sharing some common behavior
between a group of enumerations.

因此,我发现使用与您几乎相同的解决方法的* answer.我认为这是唯一的方法.

上一篇:C++核心准则T.120:只在确实有需要时使用模板元编程


下一篇:JavaBean规范是否已更新以反映注释的存在