显示为局部变量的全局变量

2024-05-19 09:34:02 发布

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

我有下面的全球词典

global configurationFileInfo_saved
configurationFileInfo_saved = {
        'True_key': 'True',
        'False_key': 'False',
        'filename': "Configuration-noMeta" + extnt,
        'os_key': "os",
        'os': "windows",
        'os_windowsCode': "windows",
        'os_linuxCode': "linux",
        'guiEnabled': 'True',
        'guiEn_key': "GUI",
        'allowCustom': 'True',
        'allowCustom_key': "allowCustomQuizConfiguration",
        'allOrPart': "a",
        'allOrPart_key': "questions_partOrAll",
        'allOrPart_allCode': "a",
        'allOrPart_partCode': "p",
        'questionAmountDivisionFactor': 2,
        'questionAmountDivisionFactor_key': "divisionFactor",
        'mode': "e",
        'mode_key': "mode",
        'mode_noDeduction_code': "noDeductions",
        'mode_allowDeductions_code': "allowDeductions",
        'deductionsPerIncorrect': 1,
        'deductionsPerIncorrect_key': "allowDeductions_pointDeduction_perIncorrectResponse",
        'loc': "C:\\Program Files (x86)\\Quizzing Application <Version>\\Admin\\Application Files\\dist\\Main\\",
        'loc_key': "location",
        'title': "Quizzing Appliaction <Version> -- By Geetansh Gautam",
        'title_key': "title"

这是访问词典的地方:

config_onBoot_keys = list(configSaved(True, False, None).keys()) config_onBoot_vals = list(configSaved(True, False, None).values())

configSaved(False, True, configurationFileInfo)

configSaved (Tempoarary function for reading andd writing):

def configSaved(get, save, saveDict):
    if get:
        return configurationFileInfo_saved
    elif save:
        configurationFileInfo_saved = saveDict

当我以后访问dictionary是一个函数时,我得到以下错误:

UnboundLocalError: local variable 'configurationFileInfo_saved' referenced before assignment

我做错了什么


Tags: keyfalsetruetitleosmodewindows词典
1条回答
网友
1楼 · 发布于 2024-05-19 09:34:02

这是因为我们只能在函数内部访问全局变量,但要进行修改,必须在函数内部使用global关键字

例如,这不会给出localbound错误:

x = 1 # global variable

def example():
    print(x)
example()

这将给出错误:

例如:

x = 1 # global variable

def example():
    x = x + 2 # increment x by 2
    print(c)
example()

要避免此错误,请执行以下操作:

x = 0 # global variable

def example():
    global x
    x = x + 2 # increment by 2
    print("Inside add():", x)

example()
print("In main:", x)

现在回答问题:

configurationFileInfo_saved = {...}

def configSaved(get, save, saveDict):
    global configurationFileInfo_saved
    if get:
        return configurationFileInfo_saved
    elif save:
        configurationFileInfo_saved = saveDict

相关问题 更多 >

    热门问题