Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的全局变量,这是正常行为吗?_Python - Fatal编程技术网

Python中的全局变量,这是正常行为吗?

Python中的全局变量,这是正常行为吗?,python,Python,我一直在使用WinPython编写一个使用全局变量的程序,代码如下: def main(): global listC listC=[1,2,3,4,5] def doSomething(): if listC!=[]: pass 我遇到的问题是,如果listC!=。。。给我一个警告,上面写着“未定义的名称列表C”;这个程序实际上可以正常编译和执行,但我想知道,如果我将list声明为全局变量,为什么会出现警告 我希望以以下方式执行: programNa

我一直在使用WinPython编写一个使用全局变量的程序,代码如下:

def main():
    global listC
    listC=[1,2,3,4,5]

def doSomething():
    if listC!=[]:
        pass
我遇到的问题是,如果listC!=。。。给我一个警告,上面写着“未定义的名称列表C”;这个程序实际上可以正常编译和执行,但我想知道,如果我将list声明为全局变量,为什么会出现警告

我希望以以下方式执行:

programName.main()       //init the list
programName.doSomething()    //do an operation with the list
programName.doSomething()     //same as before
...

谢谢

这应该可以用了。。。它对我有用

def doSomething():
   if listC != []:
       print "success!"

def main():
    global listC
    listC = [1,2,3,4,5]
    doSomething()

>>> main()
success!

根据您向我们展示的部分代码,它应该可以工作- 但是,由于您得到了错误,因此您正在
doSomething
函数体中的某个点向
listC
赋值

如果存在任何此类赋值,Python将把
listC
变量视为本地变量 若要
doSomething
,除非在函数开始时将其列为全局-当然,在本例中,您还必须在初始化它的函数中将其声明为全局-
main
,并确保初始化代码在调用doSomething之前运行

def main():
    global listC
    listC=[1,2,3,4,5]

def doSomething():
    global listC
    if listC != []:
        print "success!"
    # the following statement would trigger a NameError above, if not for the "global":
    listC = [2,3]

也错了。没有这种需要-只要它在
main
中声明为全局,并且该代码首先运行。@jsbueno当然!不知道我在想什么。。。那很好用。。。更改了我的答案…我必须同意下面的jsbueno,doSomething()中的listC肯定发生了其他事情。你发布的代码运行良好。