我认为您错误地使用了“全局”。请参阅Python参考。您应该声明不带全局变量的变量,然后在要访问全局变量的函数内部声明它global 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()