Python - 导入模块获取全局变量
Python - Importing module gets global variables
我有两个 Python 脚本,一个 testclass.py:
import numpy
zz = numpy
class Something(object):
def __init__(self):
self.xp = zz
和一个 testscript.py:
from testclass import Something
x = Something()
print(x.xp)
我预计 testscript.py 会抛出错误,因为我认为 testscript 仅导入 class Something
(使用其 __init__
方法),而不是全局变量zz
。因此,考虑到这种行为,我的问题是,从模块导入时,Python "run" 模块文件中的所有内容吗?
是的。当你执行:
from testclass import Something
等同于:
import testclass
Something = testclass.Something
更一般地说,Python 解释器无法事先知道您的模块公开了哪些对象(除非您在 __all__
中明确命名它们)。对于极端情况,请考虑以下情况:
a.py
:
import random
if random.random() > 0.5:
class Foo(object):
pass
else:
class Bar(object):
pass
运行 from a import Foo
有 50% 的几率失败,因为 a
模块对象可能有也可能没有 Foo
属性。
我有两个 Python 脚本,一个 testclass.py:
import numpy
zz = numpy
class Something(object):
def __init__(self):
self.xp = zz
和一个 testscript.py:
from testclass import Something
x = Something()
print(x.xp)
我预计 testscript.py 会抛出错误,因为我认为 testscript 仅导入 class Something
(使用其 __init__
方法),而不是全局变量zz
。因此,考虑到这种行为,我的问题是,从模块导入时,Python "run" 模块文件中的所有内容吗?
是的。当你执行:
from testclass import Something
等同于:
import testclass
Something = testclass.Something
更一般地说,Python 解释器无法事先知道您的模块公开了哪些对象(除非您在 __all__
中明确命名它们)。对于极端情况,请考虑以下情况:
a.py
:
import random
if random.random() > 0.5:
class Foo(object):
pass
else:
class Bar(object):
pass
运行 from a import Foo
有 50% 的几率失败,因为 a
模块对象可能有也可能没有 Foo
属性。