如何制作跨模块变量? [英] How to make a cross-module variable?

查看:77
本文介绍了如何制作跨模块变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__debug__变量在某种程度上很方便,因为它会影响每个模块.如果我想创建另一个工作方式相同的变量,该怎么办?

The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it?

从某种意义上说,如果我在一个模块中更改foo,则在另一个模块中对其进行更新,则该变量(可以是原始变量,并将其称为"foo")不必是真正的全局变量.如果可以在导入其他模块之前设置foo,然后它们会看到相同的值,那就好了.

The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be fine if I could set foo before importing other modules and then they would see the same value for it.

推荐答案

我不以任何方式,形状或形式认可此解决方案.但是,如果将变量添加到__builtin__模块,则可以像访问包含__builtin__的任何其他模块中的全局变量一样访问它-默认情况下,所有变量都包含在其中.

I don't endorse this solution in any way, shape or form. But if you add a variable to the __builtin__ module, it will be accessible as if a global from any other module that includes __builtin__ -- which is all of them, by default.

a.py包含

print foo

b.py包含

import __builtin__
__builtin__.foo = 1
import a

结果是打印了"1".

__builtin__模块可作为本地符号__builtins__使用-这就是其中两个答案之间存在差异的原因.另外请注意,在python3中,__builtin__已重命名为builtins.

The __builtin__ module is available as the local symbol __builtins__ -- that's the reason for the discrepancy between two of these answers. Also note that __builtin__ has been renamed to builtins in python3.

这篇关于如何制作跨模块变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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