2017-06-23 36 views
0

我是新来的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 
+0

你** **肯定认为那就是抛出异常的代码?因为按照书面,你会得到'UnboundLocalError'。 –

+0

换句话说,你*不能*得到一个'NameError',这个名字在你发布的示例代码中有明确的定义。此外,您发布的代码将分配给函数*中的名称'globlist' *,使其成为本地代码,除非用下面答案中所述的'global'语句特别覆盖。但是,只有当你发布的代码有不同的例外时,这才有意义。 –

+0

不便之处。是的,它显示以下错误'UnboundLocalError:在分配前引用的局部变量'globlist' –

回答

4

你可以这样做:

def cmplist(list): #Actually this function calls from another function 
    global globlist 
    if (len(list) > len(globlist)): 
     globlist = list[:] #copy all element of list to globlist 

这可能是更Python将它传递,虽然修改的方式。

+0

或者使用'globlist [:] = list'并放弃'global'关键字。但是,给出的例外表明了一个非常不同的问题。发布的代码和异常不匹配。 –

+0

谢谢,西蒙,它的工作原理。 –

0

您需要将其声明为全局的功能:

def cmplist(list): #Actually this function calls from another function 
    global globlist 
    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 
0

内部功能cmplist,对象globlist'是不被认为是全球范围。 Python解释器将其视为局部变量;在函数cmplist中找不到它的定义。因此错误。 函数内部声明全局列表在第一次使用之前是全局的。 像这样的工作:

def cmplist(list): 
    global globlist 
    ... # Further references to globlist 

HTH, Swanand