如果在定义了该名称的迭代范围内,未定义的变量不会引发错误

undefined variable does not raise error if in scope of iteration with that name defined

使用 CPython 3.8.2+ (984a5,执行以下代码不会引发错误。 结果是一个打印的字典,就好像它的值是具有相同存储值的实例。

class Foo(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return name  # this is undefined (missing `self.`)


optable = dict()
for name in ['a', 'b']:
    optable[name] = Foo(name)
print(optable)
print(optable['a'].name)
print(optable['b'].name)

此脚本打印

{'a': b, 'b': b}
a
b

没想到,两个表示都打印出来了,而且是"b".

这可能是 CPython 错误吗?

如评论中所述,确保 return 属于 Foo

每个实例的名称
    def __repr__(self):
        return self.name

防止 return 全局 name

此外,请务必使用 correct method 来表示对象