如何修复 Python Enum - AttributeError(name) from None 错误?

sup*_*fly 6 python enums virtualenv

尝试在 Python 3.7.3 中使用枚举,出现以下错误。已经尝试安装 - 和卸载 - enum34,但它仍然不起作用。在虚拟环境中完成所有操作(如错误所示)。

我还能做些什么来解决这个问题(除了使用另一个 enum 实现,如本问题所示)?

#enum import:
from enum import Enum

# enum definition:
class Status(Enum):
    on: 1
    off: 2

# enum utilisation (another class, same file):
self.status = Status.off

# error:
File "C:\dev\python\test\venv\lib\enum.py", line 349, in __getattr__
AttributeError(name) from None
AttributeError: off
Run Code Online (Sandbox Code Playgroud)

jwo*_*der 18

定义枚举的正确语法是:

class Status(Enum):
    on = 1
    off = 2
Run Code Online (Sandbox Code Playgroud)

不是on: 1


c0x*_*x6a 6

在您的定义中,用于=为属性赋值,而不是:.

# enum definition:
class Status(Enum):
    on = 1
    off = 2
Run Code Online (Sandbox Code Playgroud)

  • 您能否添加解释为什么OP的原始语法没有错误? (2认同)