Python模块导入:导入模块中导入的模块怎么样

时间:2013-09-04 22:01:56

标签: python import

对于提出这个可能天真的问题感到抱歉。我试图寻找文档并做一些实验,但我想确保是这样的:

如果,在文件test.py中,我有:

import module1

我在控制台中这样做:

import test

我不会在控制台中导入module1。

如果我这样做:

from test import *

此外,module1不会导入控制台。

这是对的吗? 谢谢!

2 个答案:

答案 0 :(得分:3)

import test

这只会将名称test导入当前命名空间。 test命名空间中的任何内容都可以test.whatever访问;特别是,module1可用作test.module1,但您不应该使用它。

from test import *

这会将不以test命名空间的下划线开头的所有内容导入到当前的名称空间中。由于module1test的命名空间中可用,因此会导入名称module1

答案 1 :(得分:0)

您的实验可以很容易地从shell中进行:

╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ echo "import module1" > test.py
╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ touch module1.py
╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ py
Python 2.7.5 (default, May 17 2013, 07:55:04)
[GCC 4.8.0 20130502 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.module1
<module 'module1' from 'module1.py'>
>>> from test import *
>>> module1
<module 'module1' from 'module1.py'>