为什么不能从另一个构造静态类字典?

时间:2018-10-06 04:40:44

标签: python python-3.x

从在类上下文中定义的一些dict变量开始...

class ContextFilter(logging.Filter):
    coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
        u'ERROR':u'red', u'INFO':u'blue'}
    colors =  dict(zip([u'black', u'red', u'green', u'yellow',
        u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))

...我打算生成一个派生的dict变量,该变量有效地缓存colors[coloring[____]]的结果;预期的dict内容如下所示:

{'DEBUG': '35', 'WARNING': '33', 'ERROR': '31', 'INFO': '34'}

但是,使用here中描述的两种字典构造器格式会导致NameError: name 'colors' is not defined的运行时错误消息(尽管colors是在紧前面定义的):

class ContextFilter(logging.Filter):
    coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
        u'ERROR':u'red', u'INFO':u'blue'}
    colors =  dict(zip([u'black', u'red', u'green', u'yellow',
        u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
    print(colors) # test statement; colors is in scope here
    color_map = {k:colors[v] for k, v in coloring.items()}

class ContextFilter(logging.Filter):
    coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
        u'ERROR':u'red', u'INFO':u'blue'}
    colors =  dict(zip([u'black', u'red', u'green', u'yellow',
        u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
    print(colors) # test statement; colors is in scope here
    color_map = dict([(k, colors[v]) for k, v in coloring.items()])

为什么以上代码片段的行为不符合预期?为什么colors不在color_map构造函数的范围内,即使它似乎在类声明的范围内?

(最终,我能够使用下面的代码块获得所需的行为;我要问这个问题以了解为什么我以前尝试“更清洁”的解决方案无法正常工作。)

class ContextFilter(logging.Filter):
    coloring = {u'DEBUG':u'magenta', u'WARNING':u'yellow',
        u'ERROR':u'red', u'INFO':u'blue'}
    colors =  dict(zip([u'black', u'red', u'green', u'yellow',
        u'blue', u'magenta', u'cyan', u'white'], map(str, range(30, 30 + 8))))
    color_map = {}
    for k, v in coloring.items():
        color_map[k] = colors[v]

0 个答案:

没有答案