全局变量显示为局部变量[已解决]

时间:2020-04-03 21:25:47

标签: python python-3.x

我有以下全球词典

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

稍后访问字典是一个函数时,出现以下错误:

UnboundLocalError: local variable 'configurationFileInfo_saved' referenced before assignment

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

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

例如,这不会产生本地错误:

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