【问题标题】:Variable in class scope not found in conditional dict comprehension [duplicate]在条件字典理解中找不到类范围内的变量[重复]
【发布时间】:2019-07-14 06:46:59
【问题描述】:

考虑以下代码:

class A:
    ID = 5
    VALUES = ((4, "four"), (5, "five"))
    MAP = {
        t[0]: t[1] for t in VALUES if t[0] != ID
    }

这很令人惊讶(对我来说),因为VALUES 符号被正确找到,但代码给出了错误“NameError: global name 'ID' is not defined”。

只有t[0]: t[1] for t in VALUES 有效。为什么?

【问题讨论】:

标签: python-3.x scope python-3.7


【解决方案1】:

@t.m.adam指向的问题中的主题有一个excellent and very detailed answer

简短的回答是:

类范围内的名称不可访问。名称在 最里面的封闭函数范围。如果类定义出现在 嵌套范围链,解析过程跳过类 定义。

至于解决方案,我认为实现预期结果的最简单方法是在__init__ 函数内创建变量,如下所示:

class A:
    ID = 5
    VALUES = ((4, "four"), (5, "five"))

    def __init__(self):
        self.MAP = {
            t[0]: t[1] for t in self.VALUES if t[0] != self.ID
        }

如果你打印self.MAP的结果,你会得到如下:

>>> my_instance = A()
>>> print(my_instance.MAP)
{4: 'four'}

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 2015-08-21
    相关资源
    最近更新 更多