gpt4 book ai didi

Python:未定义全局名称 'foobar'

转载 作者:行者123 更新时间:2023-11-28 21:18:34 26 4
gpt4 key购买 nike

有人可以解释为什么以下代码在第 12 行(打印语句)产生错误“global name 'foobar' is not defined”吗?我以为我了解 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()

最佳答案

Foo() 被调用时,foobar 还没有定义(直到 Foo() 返回并且它的返回值被分配给 foobar。但是,foobar 是通过 调用 Foo() 间接访问的vi 对 Bar.__init__() 的调用。因此,在执行 Bar.__init__ 中的 print foobar 时,全局 foob​​ar 尚未定义。如果您在调用 main 之前设置 foobar 的值,您将看到该值打印在 之前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 中的局部变量。

关于Python:未定义全局名称 'foobar',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26290431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com