Python_两种导入模块的方法异同

来源:互联网 发布:淘宝网店实战宝典txt 编辑:程序博客网 时间:2024/06/12 20:47
Python_两种导入模块的方法异同

Python中有两种导入模块的方法

1:import module

2:from module import *

使用from module import *方法可以导入独立的项,也可以用from module import *导入所有的东西。eg:from types import FunctionType

代码示例:

>>> from UserDict import UserDict>>> UserDict<class UserDict.UserDict at 0x015D3B90>>>> import UserDict>>> UserDict<module 'UserDict' from 'C:\Python27\lib\UserDict.pyc'>

在上面,使用from UserDict import UserDict进行模块的导入,UserDict 被直接导入到局部名字空间去了,所以它可以直接使用,而不需要加上模块名的限定。

再比如:

复制代码
>>> import types>>> types.FunctionType     ##1.types 模块不包含方法,只是表示每种 Python 对象类型的属性。注意这个属性必需用模块名 types 进行限定。<type 'function'>>>> FunctionType           ##2.FunctionType 本身没有被定义在当前名字空间中;它只存在于 types 的上下文环境中。Traceback (most recent call last):  File "<pyshell#116>", line 1, in <module>    FunctionTypeNameError: name 'FunctionType' is not defined>>> from types import FunctionType  ##3.这个语法从 types 模块中直接将 FunctionType 属性导入到局部名字空间中>>> FunctionType         ##4.FunctionType 可以直接使用,与 types 无关<type 'function'>
复制代码

总结:什么时候你应该使用 from module import

  • 如果你要经常访问模块的属性和方法,且不想一遍又一遍地敲入模块名,使用 from module import
  • 如果你想要有选择地导入某些属性和方法,而不想要其它的,使用 from module import
  • 如果模块包含的属性和方法与你的某个模块同名,你必须使用 import module 来避免名字冲突。

但是要注意的是:尽量少用 from module import * ,因为判定一个特殊的函数或属性是从哪来的有些困难,并且会造成调试和重构都更困难。

原创粉丝点击