在函数中使用全局变量 [英] Using global variables in a function

查看:129
本文介绍了在函数中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在函数中创建或使用全局变量?

How can I create or use a global variable in a function?

如果在一个函数中创建全局变量,如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要对其访问的函数的局部变量中?

If I create a global variable in one function, how can I use that global variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?

推荐答案

您可以在其他函数中使用全局变量,方法是在每个为其分配值的函数中将其声明为global:

You can use a global variable within other functions by declaring it as global within each function that assigns a value to it:

globvar = 0

def set_globvar_to_one():
    global globvar    # Needed to modify global copy of globvar
    globvar = 1

def print_globvar():
    print(globvar)     # No need for global declaration to read value of globvar

set_globvar_to_one()
print_globvar()       # Prints 1

我想这是因为全局变量是如此危险,Python希望通过显式要求global关键字来确保您确实知道这就是要使用的内容.

I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.

如果要在模块之间共享全局变量,请参阅其他答案.

See other answers if you want to share a global variable across modules.

这篇关于在函数中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆