繁体   English   中英

将枚举类分配给变量并访问它

[英]Assign Enum Class to a variable and access it

我有一个Enum班

default_enums.py

import enum

class Color(enum.Enum):
    Red = 0
    Blue = 1
    Green = 2

app.py

from default_enums import Color

def set_enums():
    global color_enum
    color_enum = Color


another_file.py

import app

#this line throws the error
# RuntimeError: no object bound to color_enum
app.color_enum.Red

我无法从color_enum访问该值,因为我已经将该类分配给color_enum。

谁能帮助我解决问题。

谢谢

您需要做的就是在app.py模块中调用set_enums()函数。

-----------app.py-----------

from default_enums import Color

def set_enums():
    global color_enum
    color_enum = Color

#call the function to set the value for color_enum 
set_enums()

-----------another_file.py-----------

from app import *

print(color_enum.Red.value)
#0

虽然如此,但我认为可以改进设计代码。 实际上不需要整个app.py模块。 而且color_enum变量不是以前定义的,而是在set_enums()函数中设置的,这可能会导致遇到您遇到的问题。

因此,我建议再次查看代码设计,而不是实现上面的设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM