UnboundLocalError:在赋值之前引用了局部变量,但它不是?全局/局部范围的问题

2024-05-08 04:08:43 发布

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

所以我知道这个问题被问了很多次,但我还没有发现任何与我所经历的事情完全相符的东西

在我的程序(Python3.7.1)中,启动时我想定义安装程序的位置,以及保存程序生成的文件的默认位置。稍后在程序中,我想再次显示这些变量,并为用户提供将默认位置更改为其他位置的选项

因此,我在全球范围内有以下代码:

import os

installedDirectory = os.getcwd()

os.chdir('C:\\Program Files')

workingDirectory = os.getcwd()

print ('Program install location = ' + installedDirectory)
print ('Working directory = ' + workingDirectory)

程序的上述部分工作正常,并给出以下结果:

Program install location = C:\Users\Chuu\AppData\Local\Programs\Python\Python37-32\Scripts Working directory = C:\Program Files

但是,在程序的后面,我在函数中调用了这些相同的变量,并为用户提供了更改变量workingDirectory的选项:

def hiimafunction():

    print ('')
    print ('Current program install location = ' + installedDirectory)
    print ('')
    print ('Current working directory where files are saved = ' + workingDirectory)
    print ('')
    print ('Where would you like files to be saved?')
    print ('')
    print ('Press 1 for the current program install location')
    print (r'Press 2 for the default startup location - C:\\Program Files')
    print ('Press 3 for a custom location')
    print ('')
    oliviahye = input()
    if oliviahye == ('1'):
        os.chdir(installedDirectory)
    elif oliviahye == ('2'):
        os.chdir('C:\\Program Files')
    elif oliviahye == ('3'):
        print ('')
        print ('Type a path where you would like to save files.')
        oliviahye = input()
        os.chdir(oliviahye)
    else:
        hiimafunction()

    workingDirectory = os.getcwd()

    print ('')
    print ('Current save location is now = ' + workingDirectory)

发生这种情况时,我会出现以下错误:

UnboundLocalError: local variable 'workingDirectory' referenced before assignment

尽管错误明确指向该行:

print ('Current working directory where files are saved = ' + workingDirectory)

…问题似乎在于函数中的这一行:

workingDirectory = os.getcwd()

如果我删除函数中的这一行,就不会有错误,但当然程序也不会执行它应该执行的操作,即获取新分配的工作目录并将其分配给变量workingDirectory。我也可以给它一个新的变量(例如workingDirectory2),它不会崩溃,但这样一来,让变量workingDirectory首先显示这些数据的目的就失败了。我不明白为什么这一行在全局范围内没有问题,但当变量已经定义时,同一行在函数中生成错误

阅读此问题,添加以下行:

global workingDirectory

进入程序的第一部分应该会有帮助,因为它应该停止程序在本地创建另一个同名变量,但它似乎没有做任何事情,因为相同的错误会产生。有人能帮忙吗


Tags: install函数程序os错误locationfilesprogram
1条回答
网友
1楼 · 发布于 2024-05-08 04:08:43

如果在函数中的任何位置为名称赋值,则该名称是整个函数的本地名称

所以,因为你有这条线:

workingDirectory = os.getcwd()

在函数中,名为workingDirectory的全局变量是否存在并不重要;当您尝试执行以下操作时:

print ('Current working directory where files are saved = ' + workingDirectory)

它检查为该名称保留的局部变量中的插槽,发现该插槽为空,并引发错误

如果要以独占方式使用全局名称(因此在分配时,全局名称已更改),请添加:

global workingDirectory

到函数顶部(在函数内部,但在函数中的所有其他代码之前),并确保在调用此函数之前(例如,在顶层分配workingDirectory = "Uninitialized"),或在函数使用之前(例如,将分配移到print之前的workingDirectory),全局地给workingDirectory一些值(使用它的人是谁)

如果您想print全局,但随后存储值而不更改它,请为本地范围的版本使用不同的名称,并且只读取全局(您不需要显式声明它global在这种情况下,只要您从未分配它,Python就假定它需要按嵌套、全局和内置范围的顺序查找它)

相关问题 更多 >