由于我使用 Python 2.6,我正在尝试创建自定义 Enum 类。我需要的是将字符串与枚举对象一起存储。像这样的东西:
class Enum(object):
def __init__(self, value):
self.value = value[0]
self.msg = value[1]
class Parameters(Enum):
SERVER_LISTEN_ADDRESS = (0, "http://blabla.com")
SERVER_LISTEN_PORT = (1, "7001")
SERVER_SSL_LISTEN_PORT = (2, "7002")
(...) # many parameters more
SERVER_NAME = (X, "name")
问题是我的“参数”类不可迭代...... 从另一个文件,我需要能够在 PARAM 之间进行迭代:
import Parameters
for param in Parameters:
# do sth
不幸的是,对于我的解决方案,我有错误:参数中的参数:
类型错误:“类型”对象不可迭代
。
最佳答案
使用向后移植的 enum
模块(documentation):
from enum import Enum
class Parameters(Enum):
PARAM1 = (0, "some msg 1")
PARAM2 = (1, "some msg 2")
for i in Parameters:
print(i, '=', i.value)
打印:
Parameters.PARAM1 = (0, 'some msg 1')
Parameters.PARAM2 = (1, 'some msg 2')
关于python - Python 2.6 中的可迭代枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816919/