我认为你使用“全局”不正确。请参见
Python reference.您应该声明变量没有全局,然后在内部的函数,当你想访问全局变量,你声明它’全局yourvar’。
#!/usr/bin/python
total
def checkTotal():
global total
total = 0
看到这个例子:
#!/usr/bin/env python
total = 0
def doA():
# not accessing global total
total = 10
def doB():
global total
total = total + 1
def checkTotal():
# global total - not required as global is required
# only for assignment - thanks for comment Greg
print total
def main():
doA()
doB()
checkTotal()
if __name__ == '__main__':
main()
因为doA()不修改全局总计输出为1不是11。