使用 from module import 导入模块



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


下面是 from module

from UserDict import UserDict


它与你所熟知的 import module 语法很相似,但是有一个重要的区别:UserDict 被直接导入到局部名字空间去了,所以它可以直接使用,而不需要加上模块名的限定。你可以导入独立的项或使用 frommodule



python中from turtle import python中from turtle import怎么用_Perl

Python 中的 from module 像 Perl 中的 use module ;Python 中的 import module 像 Perl 中的 require module


python中from turtle import python中from turtle import怎么用_Perl

Python 中的 from module 像 Java 中的 import module.* ;Python 中的 import module 像 Java 中的 import module

import module vs. from module



>>> import
>>> 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                   <type 'function'>



python中from turtle import python中from turtle import怎么用_Perl_03

types 模块不包含方法,只是表示每种 Python 对象类型的属性。注意这个属性必需用模块名 types

python中from turtle import python中from turtle import怎么用_Java_04

FunctionType 本身没有被定义在当前名字空间中;它只存在于 types

python中from turtle import python中from turtle import怎么用_Python_05

这个语法从 types 模块中直接将 FunctionType

python中from turtle import python中from turtle import怎么用_Perl_06

现在 FunctionType 可以直接使用,与 types


from module?


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


Python



python中from turtle import python中from turtle import怎么用_Python_07

尽量少用 from module import *