我的部分代码不断收到此错误。

Traceback (most recent call last):
File "./mang.py", line 1688, in <module>
files, tsize = logger()
File "./mang.py", line 1466, in logger
nl = sshfile(list, "nl")
UnboundLocalError: local variable 'sshfile' referenced before assignment


我没有编写代码,因为它在函数之间来回移动。我想知道是否有人可以告诉我为什么python会吐出这个错误? sshfile不是变量,而是一个类。

最佳答案

您可能尚未导入包含sshfile定义的文件,或者您需要使用包名来限定类名。这取决于您如何导入。

它来自什么包装?它在哪里定义?



更新资料

对于任何其他阅读此内容的人,在评论中进行讨论后,发现问题在于名称sshfile在函数中进一步用作变量名,如下所示:

class sshfile:
    pass

def a():
    f = sshfile() # UnboundLocalError here
    sshfile = 0

a()


解决方案是不要使用隐藏您需要使用的类名的变量名。

08-06 20:57