我认为您错误地使用了“全局”。请参阅Python参考。您应该声明不带全局变量的变量,然后在要访问全局变量的函数内部声明它
global yourvar。
#!/usr/bin/pythontotaldef checkTotal(): global total total = 0
请参阅以下示例:
#!/usr/bin/env pythontotal = 0def doA(): # not accessing global total total = 10def doB(): global total total = total + 1def checkTotal(): # global total - not required as global is required # only for assignment - thanks for comment Greg print totaldef main(): doA() doB() checkTotal()if __name__ == '__main__': main()
因为
doA()不修改 全局总数, 所以输出为1而不是11。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)