【问题标题】:Python: global name 'foobar' is not definedPython:未定义全局名称“foobar”
【发布时间】:2014-12-05 02:13:26
【问题描述】:

有人能解释一下为什么下面的代码在第 12 行(打印语句)会产生错误“未定义全局名称 'foobar'”吗?我以为我理解 Python 中的范围,但这让我很适应。

def main():
  # initialize
  global foobar
  foobar = Foo()

class Foo():
  def __init__(self):
    self.bar = Bar()

class Bar():
  def __init__(self):
    print foobar

#Call main() when script is executed
if __name__ == '__main__': main()

【问题讨论】:

  • 您似乎期待global foobar“声明”一个变量并将其初始化为默认值?变量在 Python 中不是这样工作的。所有global 的意思是“当您看到对该变量的分配时,将其分配为全局而不是局部”。在这样的分配发生之前,仍然没有变量。

标签: python scope globals


【解决方案1】:

在调用Foo() 时,foobar 尚未定义(直到Foo() 返回并将其返回值分配给foobar。但是,foobar 被访问通过调用Foo(),间接调用Bar.__init__()。因此,在执行Bar.__init__中的print foobar时,尚未定义全局foobar。如果您设置foobar 在调用 main 之前的值,您将看到在分配 Foo 对象之前打印的值。尝试以下操作

if __name__ == "__main__":
    foobar = 3
    foobar = Foo()  # This will output "3"
    print foobar    # This will print something like <__main__.Foo object at 0x.....>

正如 abarnert 指出的那样,global foobar 不会创建变量 foobar;它只是确保由以下赋值创建的变量是在全局范围内创建的,而不是作为main 中的局部变量。

【讨论】:

  • 我感觉可能是这样。谢谢。
【解决方案2】:

global foobar 需要引用已经存在的foobar。

例如

foobar = 0

def foo ():
    global foobar
    print (foobar) #python 3

【讨论】:

    猜你喜欢
    • 2011-05-03
    • 2017-02-03
    • 2013-08-23
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2013-07-28
    相关资源
    最近更新 更多