Python中的枚举组成

时间:2019-01-04 20:38:16

标签: python python-3.x enums

我很难在Python中找到OO Enum组成的示例。因此,我想问以下示例是否正确,还是建议使用更多的pythonic方法?

在声明Enum时,我更喜欢使用类语法,但对于组合功能API似乎是可取的。使用类语法可以做到这一点吗?

from enum import Enum


class Vertical(Enum):

    Tall = 1
    Short = 2


class Horizontal(Enum):

    Slim = 1
    Spacious = 2


composition = list(Vertical.__members__)
composition.extend(Horizontal.__members__)

Body = Enum('Body', composition)

1 个答案:

答案 0 :(得分:1)

您不能派生枚举,它们是“密封的”:

class Body(Vertical): pass

通向TypeError: Cannot extend enumerations


如果您希望组成的枚举相等,则可以使用IntEnum

from enum import IntEnum 

class Vertical(IntEnum ):
    Tall = 1
    Short = 2 

class Horizontal(IntEnum):  # distinct int's
    Slim = 3
    Spacious = 4 

composition = list(Vertical.__members__)
composition.extend(Horizontal.__members__)

Body = IntEnum('Body', composition)

用法:

print(Body.Tall == Vertical.Tall)  # True
print(Body.Tall == 1)              # Also True

从本质上讲,它可以归结为:您的枚举现在也是int的。不过,您需要注意不要将相同的整数赋予不同的概念:

class Sizes(IntEnum):
    Tiny = 1

print(Sizes.Tiny == Vertical.Tall)  # True - but not really?