html tool

2013年3月26日星期二

Dive into Python 的我的翻译 XXXVIII------8.5 IX


[原文]P110
Remember the difference between from module import and import module?
With import module, the module itself is imported, but it retains its own namespace, which is why you need to use the module name to access any of its functions or attributes: module.function.

[popexizhi] import module ,导入模块全部的命名空间使用 module.function方式访问


But with from module import, you're actually importing specific functions and attributes from another module into your own namespace, which is why you access them directly without referencing the original module they came from. With the globals function, you can actually see this happen.
[popexizhi] from module import 导入的functions 和attributes访问时就不需要使用the original module they came from了。


[pope译]还记得 from module import 和 import module 有什么区别吗?
使用import module,模块自身被导入,但它保留了自己的命名空间,这就是你为什么要使用模块名称 来访问它的函数和属性:module.function.
但使用from module import,你实际上只导入了指定的函数和属性到你自己的命名空间中,这也是你为什么可以直接访问而不用指定它们的来源模块。使用globals函数,你就会看到这个了。
[?]想起一个问题,如果from module Import 导入的内容中与当前命名空间有重名的定义内容,会发生什么呢?报错?提示修改?直接导入,引用时提示选择引用哪个?experment 一下,我使用文件自身的复制版导入文件自身。没看到报错,正常运行,why?

[net 译 来源:http://woodpecker.org.cn/diveintopython/html_processing/locals_and_globals.html]
回想一下 from module import  import module 之间的不同。使用 import module,模块自身被导入,但是它保持着自已的名字空间,这就是为什么您需要使用模块名来访问它的函数或属性:module.function 的原因。但是使用 from module import,实际上是从另一个模块中将指定的函数和属性导入到您自己的名字空间,这就是为什么您可以直接访问它们却不需要引用它们所来源的模块。使用 globals 函数,您会真切地看到这一切的发生。

没有评论:

发表评论