gpt4 book ai didi

python - 嵌套模块重新导入时出现 UnboundLocalError

转载 作者:太空狗 更新时间:2023-10-30 01:37:42 27 4
gpt4 key购买 nike

当我在 python 2.7 中重新导入一个已经导入的模块时,我得到一个 UnboundLocalError。一个最小的例子是

#!/usr/bin/python

import sys

def foo():
print sys
import sys

foo()

Traceback (most recent call last):
File "./ptest.py", line 9, in <module>
foo()
File "./ptest.py", line 6, in foo
print sys
UnboundLocalError: local variable 'sys' referenced before assignment

然而,当嵌套导入作为函数定义中的第一条语句放置时,一切正常:

#!/usr/bin/python

import sys

def foo():
import sys
print sys

foo()

<module 'sys' (built-in)>

有人可以解释为什么第一个脚本失败吗?谢谢。

最佳答案

这与引用全局变量相同。在 Python FAQ 中有很好的解释

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

关于python - 嵌套模块重新导入时出现 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34311814/

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