我是新来的Python,在此之前,我用的是C.的Python - 访问全局列表功能
def cmplist(list): #Actually this function calls from another function
if (len(list) > len(globlist)):
globlist = list[:] #copy all element of list to globlist
# main
globlist = [1, 2, 3]
lst = [1, 2, 3, 4]
cmplist(lst)
print globlist
当我执行这个代码,它显示了以下错误
if (len(list) > len(globlist)):
NameError: global name 'globlist' is not defined
我想从函数访问和修改globlist,而不用将其作为参数传递。在这种情况下,输出应该是
[1, 2, 3, 4]
任何人都可以帮助我找到解决方案吗?
总是欢迎任何建议和更正。 在此先感谢。
编辑: 感谢Martijn Pieters的建议。 原始误差
UnboundLocalError: local variable 'globlist' referenced before assignment
你** **肯定认为那就是抛出异常的代码?因为按照书面,你会得到'UnboundLocalError'。 –
换句话说,你*不能*得到一个'NameError',这个名字在你发布的示例代码中有明确的定义。此外,您发布的代码将分配给函数*中的名称'globlist' *,使其成为本地代码,除非用下面答案中所述的'global'语句特别覆盖。但是,只有当你发布的代码有不同的例外时,这才有意义。 –
不便之处。是的,它显示以下错误'UnboundLocalError:在分配前引用的局部变量'globlist' –