Python全局变量范围 [英] Python global variable scoping

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

问题描述

我尝试在某些函数中声明一些全局变量,并将这些函数的文件导入到另一个函数中。但是,我发现在第二个文件中运行该函数不会创建全局变量。我试着用相同的名字创建另一个变量,但是当我打印出变量时,它打印出第二个文件的值,而不是全局值

globals.py

  def default():
全局值
值= 1


$ b

main.py

  from globals导入* 
值= 0
def main():
default()
打印值

if __name __ =='__ main__':
main()

如果我没有 value = 0 在main中,程序会出错(值未定义)。

如果我在 globals.py 外部声明的函数中, main.py 将取得全局的值,而不是 default()



得到 value 在python中是一个全局变量吗?

解决方案

Python中的全局变量只对它们的模块是全局的。没有可以修改的名称,这些名称对整个流程来说是全球性的。



您可以使用此功能完成您的任务:

globals.py:

  value = 0 
def default():
global值
值= 1

main.py:

 导入全局变量
def main():
globals.default()
print globals.value

如果__name__ ==__main__:
main()

我不知道是否不过,像这样的全球化是解决问题的最佳方式。

Im trying to declare some global variables in some functions and importing the file with those functions into another. However, I am finding that running the function in the second file will not create the global variable. I tried creating another variable with the same name, but when i print out the variable, it prints out the value of the second file, not the global value

globals.py

def default():
    global value
    value = 1

main.py

from globals import *
value = 0
def main():
    default()
    print value

if __name__=='__main__':
    main()

this will print 0. if i dont have value = 0 in main, the program will error (value not defined).

If i declare value in globals.py outside of the function, main.py will take on the value of the global value, rather than the value set in default()

What is the proper way to get value to be a global variable in python?

解决方案

Globals in Python are only global to their module. There are no names that you can modify that are global to the entire process.

You can accomplish what you want with this:

globals.py:

value = 0
def default():
    global value
    value = 1

main.py:

import globals
def main():
    globals.default()
    print globals.value

if __name__ == "__main__":
    main()

I have no idea whether a global like this is the best way to solve your problem, though.

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

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