无法使用Mixin类扩展python IntEnum

时间:2019-03-29 15:30:39

标签: python python-3.x enums

编辑:事实证明,这只是从3.7.1开始已修复的错误。

如果我创建一个mixin类并尝试将其添加到IntEnum中,则会出现此错误:

>>> from enum import IntEnum
>>> class Mixin:
...  pass
...
>>> class C(Mixin, IntEnum):
...  A=1
...  B=2
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\enum.py", line 211, in __new__
    enum_member = __new__(enum_class)
TypeError: object.__new__(C) is not safe, use int.__new__()

这也不起作用(相同的错误):

from enum import IntEnum

class M: ...

class C(M, IntEnum): ...

class D(C):
 A=1
 B=2

docs seem to indicate应该可行,并且确实适用于常规Enum

>>> from enum import Enum
>>> class Mixin:
...  pass
...
>>> class D(Mixin, Enum):
...  A=1
...  B=2
...
>>>

不确定这是错误还是IntEnum的限制。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

此错误自Python 3.7.1起已得到修复。