Python跨模块和全局变量导入 [英] Python imports across modules and global variables
问题描述
我有一个似乎相当基本的问题,但我似乎无法在任何地方找到任何帮助。
I have a question which seems to be rather fundamental but I can't seem to find any help on this anywhere.
file_a.py >>
from xyz import XYZ
class A:
.
.
.
file_b.py >>
import file_a
from file_a import A
class B(A):
def __init__(self):
A.__init__(self)
def someMethod(self):
XYZ.doSomething()
XYZ.doSomething()无法说NameError:名称'XYZ'未定义
即使从file_a完成的标准导入(如'import sys')似乎也无法使其在file_b中可用。我认为应该工作。我的理解错了吗?如果是,那么有没有办法在文件中包含常见的导入和全局变量? (如果它有帮助,我一直是C ++和java程序员,我现在开始使用python。)
XYZ.doSomething() fails saying NameError: name 'XYZ' is not defined Even standard imports like 'import sys' done from file_a does not seem to render it usable in file_b. I assumed that should work. Is my understanding wrong? If yes, then is there a way to have common imports and global variables across files? (If it is of nay help, I've been a C++ and java programmer and am now starting to use python. )
推荐答案
我的理解错了吗?
Is my understanding wrong?
是的,因为来自file_a import的行 A
只导入 A
类 file_b
的命名空间。 file_a
的命名空间不变。如果它不是这样,那么两种语法都没有意义:
Yes, because the line from file_a import A
import only class A
into the namespace of file_b
. The namespace of file_a
is left alone. If it were not like this, there would be little sense in having both syntax:
import modulename
from modulename import something
好像你的想法是正确的,然后在第二种形式之后你总是可以使用 modulename.someotherthing
。
as if your thinking was right, then after the second form you would always be able to use modulename.someotherthing
.
如果是,那么有没有办法进行常见的进口和文件中的全局变量?
If yes, then is there a way to have common imports and global variables across files?
是的,使用星号 *
运算符:
Yes, with the star *
operator:
from modulename import *
但这会带来命名空间污染问题,例如来自file_a import * 的将导入
file_b
还在 file_a
中完成所有导入。你将最终失去对你的进口的控制权,这会在某个时候咬你...相信我这个!
but this brings the issue of namespace pollution, for example from file_a import *
will import in file_b
also all the imports done in file_a
. You will eventually lose control of your imports and this will bite you at some time... trust me on this!
当出于某种原因需要来自模块导入*
,命名空间污染的解决方法是在模块中定义
变量 __ all __
,将应导入的内容列入白名单与明星运营商合作。
When for some reason from module import *
is needed, a workaround to namespace pollution is to define in module
the variable __all__
, which whitelists what should be imported with the star operator.
HTH!
这篇关于Python跨模块和全局变量导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!