无聊之人--除了技术,还是技术,你懂得
分类: Python/Ruby
2011-07-01 23:37:51
5.2. Importing Modules Using from module import
5.2 使用from module import来导入模块
Python has two ways of importing modules. Both are useful, and you should know when to use each. One way, import module, you've already seen in Section 2.4, “Everything Is an Object”. The other way accomplishes the same thing, but it has subtle and important differences.
Python中导入模块有两种方式。两种都非常有用,因此你需要知道何时应该使用那一种。一种方式是,import module,在2.4章,所有的东西都是对象中你已经看到。另一种方式,完成了同样的功能,但是这种方式同前一种方式相比有细微和重要的不同。
Here is the basic from module import syntax:
导入模块的基本语法
This is similar to the import module syntax that you know and love, but with an important difference: the attributes and methods of the imported module types are imported directly into the local namespace, so they are available directly, without qualification by module name. You can import individual items or use from module import * to import everything.
上面的语法同你知道和喜欢的import module 的语法类似,但是有一个十分重要的不同:被导入模块types的属性和方法被直接导入本地的名称空间,因此他们是直接可用,不需要使用模块名来限定。你可以导入单独的项或是使用from module import * 来导入所有的对象。
|
|
|
from module import * in Python is like use module in Perl; import module in Python is like require module in Perl. Python 中的from module import * 同Perl中的use module 类似;而Python中的import module 同Perl中的require module类似。 |
|
|
|
|
from module import * in Python is like import module.* in Java; import module in Python is like import module in Java. Python中的from module import * 同java中的import module * 类似; 而Python中的import module同java中的java中的import module。 |
|
Example 5.2. import module vs. from module import
例5.2 import module与from module import
The types module contains no methods; it just has attributes for each Python object type. Note that the attribute, FunctionType, must be qualified by the module name,types. Type 模块不包含任何方法:对于任意的Python对象的类型,它都含有属性。注意属性:FunctionType,必需使用模块名称来限定。 |
|
FunctionType by itself has not been defined in this namespace; it exists only in the context of types. FunctionType本身没有定义在名称空间中,它仅包含在types的上下文环境中。 |
|
This syntax imports the attribute FunctionType from the types module directly into the local namespace. 该语法导入了属性FunctionType,从types模块中直接导入本地的名称空间。 |
|
Now FunctionType can be accessed directly, without reference to types. 现在可以直接访问属性,FunctionType,不需要引用模块types. |
When should you use from module import?
那么何时使用from module import?
Other than that, it's just a matter of style, and you will see Python code written both ways.
除了上面的原因,这两个方法进仅是编程方式的不同,在Python代码中你将同时使用两种方式。
|
|
|
Use from module import * sparingly, because it makes it difficult to determine where a particular function or attribute came from, and that makes debugging and refactoring more difficult. from module import *不能放心被放心的使用 ,这是因为这种方式是的判读某个特定的函数或是属性名字来子那里更加的困难,同时也使得调试和重构变得更加的困难。 |
|