嵌套模块reimp上的UnboundLocalError

2024-04-24 02:42:59 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在Python2.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)>

有人能解释一下为什么第一个脚本失败了吗? 谢谢。你知道吗


Tags: 模块inpyimportbinfoousrdef
2条回答

这与引用全局变量相同。这在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.

对于这种情况,很难理解的是,当您在一个范围内导入某些内容时,会有一个隐式赋值。(在这种情况下实际上是重新分配)。你知道吗

事实上,import sys存在于foo中意味着,在foo中,sys不是指全局sys变量,而是指一个单独的局部变量,也称为sys。你知道吗

相关问题 更多 >