Python 显示为局部变量的全局变量
我有下面的全球词典Python 显示为局部变量的全局变量,python,python-3.x,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_wi
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"
当我以后访问dictionary是一个函数时,我得到以下错误:
UnboundLocalError:分配前引用的局部变量“configurationFileInfo\u saved”
我做错了什么?这是因为我们只能在函数中访问全局变量,但要进行修改,必须在函数中使用全局关键字 例如,这不会给出localbound错误:
x=1#全局变量
def示例():
打印(x)
示例()
这将给出错误:
例如:
x=1#全局变量
def示例():
x=x+2#增加x乘以2
印刷品(c)
示例()
要避免此错误,请执行以下操作:
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
显示您的实际使用情况。理想情况下,你的帖子应该在全局范围内包含一个
global
。您能说明函数外部的global语句如何产生UnboundLocalError
异常吗?@jordanm它不会。但是OP似乎在全局范围内使用global语句,期望这意味着变量在任何地方都是全局的。然后他们“在函数中使用它”,当然,他们还没有证明这一点,他们必须提供一个。在这种情况下,OP可能需要在函数中使用全局声明。或者更好,但不依赖于全局可变state@jordanm我已经添加了一些例子来解决您的担忧。如果仍然错误,请告诉我,我将删除答案并阅读更多相关内容。:)全局变量在所有函数之外声明。我的意思是我不能访问任何函数中的变量。你可以访问它,但不能修改它。
configurationFileInfo_saved = {...}
def configSaved(get, save, saveDict):
global configurationFileInfo_saved
if get:
return configurationFileInfo_saved
elif save:
configurationFileInfo_saved = saveDict