python 导入(转)

1. import module

2.  from module import

http://woodpecker.org.cn/diveintopython/object_oriented_framework/importing_modules.html

Python 有两种导入模块的方法。两种都有用,你应该知道什么时候使用哪一种方法。一种方法,import module,你已经在第 2.4 节 “万物皆对象”看过了。另一种方法完成同样的事情,但是它与第一种有着细微但重要的区别。

下面是 from module import 的基本语法:


from UserDict import UserDict

它与你所熟知的 import module 语法很相似,但是有一个重要的区别: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             
1
<type 'function'>
>>> FunctionType                   
2
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
NameError: There is no variable named 'FunctionType'
>>> from types import FunctionType 
3
>>> FunctionType                   
4
<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 * ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。
原文地址:https://www.cnblogs.com/phoenix13suns/p/2797835.html