【问题标题】:Use enum instances in another class in Python3在 Python3 的另一个类中使用枚举实例
【发布时间】:2018-09-06 08:42:27
【问题描述】:

我有一个名为 UsedPlatforms 的枚举类:

from enum import Enum

class UsedPlatforms(Enum):
    PROD = 1,
    TEST = 2

我想在另一个 python 类中使用这个枚举,例如:

import UsedPlatforms

def foo(platform):
    if platform == UsedPlatforms.PROD:
        print("Did it!")

foo(platform=UsedPlatforms.PROD)

但是当我运行第二个脚本时,我得到一个错误,例如:

Traceback (most recent call last):
  File "/home/user/Projects/EnumTest/test.py", line 9, in <module>
    foo(platform=UsedPlatforms.PROD)
AttributeError: module 'UsedPlatforms' has no attribute 'PROD'

Process finished with exit code 1

我认为我无法正确导入我的枚举类,或者我不知道如何在类之间使用枚举,或者什么。那么,我应该怎么做才能在其他类中使用我的枚举类呢?

谢谢!

【问题讨论】:

  • 你不需要在值后面加逗号,否则你会得到一个tuple值——即PROD == (1, )

标签: python-3.x enums


【解决方案1】:

如果您的enum 类包含在名为UsedPlatform.py 的文件中,那么您应该将test.py 中的import 语句更改为:

from UsedPlatforms import UsedPlatforms

如果您尝试导入的文件位于您需要的文件夹中:

from folder.FileWithoutExtension import <ClassName/Enum>

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    相关资源
    最近更新 更多