当我阅读答案时我仍然觉得很奇怪,所以我尝试了下面的代码示例。
首先,尝试构建以下文件结构:
tmpdir
|A
|__init__.py
| B.py
| C.py
现在 A 是 a package
,并且B
orC
是 a module
。所以当我们在 ipython 中尝试这样的代码时:
二、在ipython中运行示例代码:
In [2]: kk = __import__('A',fromlist=['B'])
In [3]: dir(kk)
Out[3]:
['B',
'__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'__path__']
看起来 fromlist 就像我们预期的那样工作。但是当我们尝试在module
. 假设我们有一个名为 C.py 的模块和其中的代码:
handlers = {}
def hello():
print "hello"
test_list = []
所以现在我们尝试在它上面做同样的事情。
In [1]: ls
C.py
In [2]: kk = __import__('C')
In [3]: dir(kk)
Out[3]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'handlers',
'hello',
'test_list']
那么当我们只想导入 test_list 的时候,它有效吗?
In [1]: kk = __import__('C',fromlist=['test_list'])
In [2]: dir(kk)
Out[2]:
['__builtins__',
'__doc__',
'__file__',
'__name__',
'__package__',
'handlers',
'hello',
'test_list']
结果表明,当我们尝试在 amodule
而不是 a上使用 fromlist 时package
, fromlist 参数根本没有帮助,因为module
已经编译了。一旦导入,就无法忽略其他的。