如何在导入的模块之间共享全局变量? [英] How to share globals between imported modules?

查看:133
本文介绍了如何在导入的模块之间共享全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模块,a.py和b.py.我希望a.py中的全局变量在b.py中可用,例如:

I have two modules, a.py and b.py. I want the globals from a.py to be available in b.py like this:

a.py:

#!/usr/bin/env python
var = "this is global"
import b
b.foo()

b.py:

#!/usr/bin/env python
var = "this is global"
def foo():
    print var

当前,我在每个模块中重新声明全局变量.必须有一种更简单的方法.

Currently, I re-declare the globals in each module. There must be an easier way.

推荐答案

如果需要的话,创建一个具有共享全局变量的设置模块.这样,您只需一次导入和引用每个全局变量,并将它们隔离在settings模块的命名空间中.这是一件好事.

Create a settings module that has shared globals if that's what you want. That way you're only importing and referencing each global one time, and you're keeping them isolated within the namespace of the settings module. It's a good thing.

#settings.py
var = 'this is global'

# a.py
import settings
import b
b.foo()

# b.py
import settings
def foo():
    print settings.var

这篇关于如何在导入的模块之间共享全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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