【发布时间】:2019-09-30 18:24:05
【问题描述】:
拿这个简单的代码:
class A(object):
numbers = [1, 2, 3]
numberscopy = numbers[:]
print(*(a for a in numberscopy))
print(*(a for a in numberscopy if a in numbers))
我在类中定义了numbers 变量。然后我可以用它来做其他事情,比如制作副本、迭代它并打印它的内容。
但最后一行,for-if 语句,以NameError: global name 'numbers' is not defined 失败。不是numberscopy,只是numbers。
我在 python 2.7.14+(导入了print_function)和 3.7.0 上都试过了,结果相同。
为什么会这样?它打算以这种方式工作吗?
【问题讨论】:
-
我得到了同样的错误——没有缩进问题。我可以打印
numbers和numberscopy,但是当我将if添加到理解中时会引发错误。这可以正常工作:print(*(a for a in numberscopy if a in A.numbers)) -
@ToothpickAnemone 仅作为示例。在实际案例中,我想根据涉及先前变量的
forif语句定义其他类变量。 -
对不起,我以为是函数。但这是一堂课。它是重复的
标签: python scope class-variables