在创建它们的函数中使用全局变量 [英] Using global variables in a function other than the one that created them

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

问题描述

如果我在一个函数中创建一个全局变量,我怎么能在另一个函数中使用该变量?

我需要将全局变量存储在需要访问它的函数的局部变量中吗?

If I create a global variable in one function, how can I use that 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 in other functions by declaring it as global in each function that assigns 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希望通过明确地要求全局关键字。

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天全站免登陆