Python 全局变量作用域 [英] Python global variable scoping

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

问题描述

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

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()

这将打印 0.如果我在 main 中没有 value = 0,程序将出错(值未定义).

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

如果我在函数外部的 globals.py 中声明 valuemain.py 将采用全局 value,而不是 default()

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()

在python中让value成为全局变量的正确方法是什么?

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

推荐答案

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:

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