ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 5.2. 使用 `from _module_ import` 导入模块 Python 有两种导入模块的方法。两种都有用,你应该知道什么时候使用哪一种方法。一种方法,`import _module_`,你已经在[第 2.4 节 “万物皆对象”](../getting_to_know_python/everything_is_an_object.html "2.4. 万物皆对象")看过了。另一种方法完成同样的事情,但是它与第一种有着细微但重要的区别。 下面是 `from _module_ import` 的基本语法: ``` from UserDict import UserDict ``` 它与你所熟知的 [`import _module_`](../getting_to_know_python/everything_is_an_object.html#odbchelper.import "例 2.3. 访问 buildConnectionString 函数的 doc string") 语法很相似,但是有一个重要的区别:`UserDict` 被直接导入到局部名字空间去了,所以它可以直接使用,而不需要加上模块名的限定。你可以导入独立的项或使用 `from _module_ import *` 来导入所有东西。 > 注意 > Python 中的 `from _module_ import *` 像 Perl 中的 `use _module_` ;Python 中的 `import _module_` 像 Perl 中的 `require _module_` 。 > 注意 > Python 中的 `from _module_ import *` 像 Java 中的 `import _module_.*` ;Python 中的 `import _module_` 像 Java 中的 `import _module_` 。 ## 例 5.2. `import _module_` _vs._ `from _module_ import` ``` >>> import types >>> types.FunctionType <type 'function'> >>> FunctionType Traceback (innermost last): File "<interactive input>", line 1, in ? NameError: There is no variable named 'FunctionType' >>> from types import FunctionType >>> FunctionType <type 'function'> ``` | | | | --- | --- | | \[1\] | `types` 模块不包含方法,只是表示每种 Python 对象类型的属性。注意这个属性必需用模块名 `types` 进行限定。 | | \[2\] | `FunctionType` 本身没有被定义在当前名字空间中;它只存在于 `types` 的上下文环境中。 | | \[3\] | 这个语法从 `types` 模块中直接将 `FunctionType` 属性导入到局部名字空间中。 | | \[4\] | 现在 `FunctionType` 可以直接使用,与 `types` 无关了。 | 什么时候你应该使用 `from _module_ import`? * 如果你要经常访问模块的属性和方法,且不想一遍又一遍地敲入模块名,使用 `from _module_ import`。 * 如果你想要有选择地导入某些属性和方法,而不想要其它的,使用 `from _module_ import`。 * 如果模块包含的属性和方法与你的某个模块同名,你必须使用 `import _module_` 来避免名字冲突。 除了这些情况,剩下的只是风格问题了,你会看到用两种方式编写的 Python 代码。 > 小心 > 尽量少用 `from module import *` ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。 ## 进一步阅读关于模块导入技术 * eff-bot 有更多关于 [`import _module_` _vs._ `from _module_ import`](http://www.effbot.org/guides/import-confusion.htm) 的论述。 * _Python Tutorial_ 讨论了高级的导入技术,包括 [`from _module_ import *`](http://www.python.org/doc/current/tut/node8.html#SECTION008410000000000000000)。