脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python之try无法使用全局变量的问题解决

Python之try无法使用全局变量的问题解决

2024-08-21 20:30Looooking Python

当我们使用try语句时,如果在try中使用了全局变量,但又在except或finally中修改了这个全局变量,就会出现这种无法修改全局变量的情况,下面就来解决一下这个问题,感兴趣的可以了解一下

其实,如果没有在 except 异常处理中对变量进行修改时,这段示例是可以正常运行的。

global_var = "hello world"

def test():
    try:
        print(global_var)
    except Exception as e:
        print(e)


if __name__ == '__main__':
    test()  # hello world

我自己希望当出现异常时,就在异常处理块中对变量进行重新赋值:

global_var = "hello world"

def test():
    try:
        print(global_var)  # cannot access local variable 'global_var' where it is not associated with a value
    except Exception as e:
        global_var = "something wrong"
        print(e)


if __name__ == '__main__':
    test()  # hello world

结果报错提示无法使用本地变量,可我明明把变量放在了最外层的,那这是怎么回事呢?

原因:在 Python 当中,当我们使用 try 语句时,如果在 try 中使用了全局变量,但又在 except 或 finally 中修改了这个全局变量,就会出现这种无法修改全局变量的情况。这是因为 try 中使用全局变量时,会创建一个局部变量与其进行绑定,而不是直接引用全局变量。

因此,我们需要使用 global 关键字声明全局变量,让 try 中的局部变量与外部的全局变量进行绑定,然后就可以在异常处理中对变量进行修改操作了。

import traceback

global_var = "hello world"

def test():
    global global_var
    try:
        print(global_var)
        raise global_var
    except Exception as e:
        global_var = "something wrong"
        # print(e)


if __name__ == '__main__':
    test()  # hello world
    test()  # something wrong

到此这篇关于Python之try无法使用全局变量的问题解决的文章就介绍到这了,更多相关Python try无法使用全局变量内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

延伸 · 阅读

精彩推荐