您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在python中分配错误之前引用

在python中分配错误之前引用

我认为您错误地使用了“全局”。请参阅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()

因为doA()修改 全局总数, 所以输出为1而不是11。

python 2022/1/1 18:38:11 有240人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶