简体   繁体   English

python中真正的全局变量

[英]Truly Global Variable in python

OK so the project I am working on requires* using a truly global variable (or five) and the other questions on here have to do with cross module variables (could be helpful later just not yet).好的,所以我正在处理的项目需要*使用一个真正的全局变量(或五个),这里的其他问题与跨模块变量有关(稍后可能会有所帮助,但目前还没有)。

Here is my problem: I have a program that will be running an environmental simulation and I need to set some global variables to be used and modified inside some of the functions.这是我的问题:我有一个程序将运行环境模拟,我需要设置一些全局变量以在某些函数中使用和修改。 How would one go about doing that?怎么会去做呢?

*When I say require I mean that I haven't found a more efficient way to do this. *当我说需要时,我的意思是我还没有找到更有效的方法来做到这一点。

Yes, there is a way to use and modify global variables inside functions that are spread across several modules.是的,有一种方法可以使用和修改分布在多个模块中的函数内的全局变量。 Put the variables in a module and import that module into your main program:将变量放在一个模块中并将该模块导入到您的主程序中:

# globals.py
klaatu = "Once in Persia reigned a king ..."

# main_program.py
import globals

def modify_klaatu():
    print globals.klaatu
    globals.klaatu = "It was the best of times, it was the worst of times."

A somewhat dodgy but entirely dynamic variant of @rob's approach: @rob 方法的一个有点狡猾但完全动态的变体:

import types
import sys

sys.modules['myglobals'] = types.ModuleType('myglobals')
sys.modules['myglobals'].__dict__.update({'first': 'thing', 'second': 'thing'})

import myglobals
print(myglobals.first) # prints 'thing'

Or if you've only got one global, how about this extremely dodgy approach:或者,如果您只有一个全局变量,那么这种极其狡猾的方法如何:

import sys
sys.modules['myglobal'] = 'thing'

import myglobal
print(myglobal) # prints 'thing'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM