如何修复 Python enum 'TypeError: Error when calling the metaclass bases: module.__init__() takes at most 2 arguments (3 given)'

问题:

你想像这样从 enum 继承一个 Python class

broken_enum_example.py
import enum

class MyEnum(enum):
    X = 1
    Y = 2class

但当你尝试运行它时,你看到类似这样的错误消息:

enum_traceback.txt
Traceback (most recent call last):
    File "test.py", line 3, in <module>
        class MyEnum(enum):
TypeError: Error when calling the metaclass bases
        module.__init__() takes at most 2 arguments (3 given)

解决方案

你不是在尝试从 Enum 类(大写 E!)继承,而是从 enum 模块继承!

这是正确的语法:

fixed_enum_example.py
from enum import Enum
class MyEnum(Enum):
    X = 1
    Y = 2

Check out similar posts by category: Python