2010-06-21 42 views
2

我注意到了这一点。例如:我在哪里可以阅读关于Python中的import _ {module name}?

创建名为例如一个空文本文件ast.py

$ touch ast.py 

运行Python

$ python 
>>> from ast import * 
>>> dir() 
['__builtins__', '__doc__', '__name__', '__package__'] 
>>> from _ast import * 
>>> dir() 
['AST', 'Add', 'And', 'Assert', 'Assign', ...] 

AST是一个python模块。那么......这里发生了什么?我尝试了一个空的os.py并没有工作。

回答

3

没有什么特别有_xxx模块只是它们私人(例如_abcoll)或低水平(例如_thread),而不是意在一般的使用。

_ast模块是特殊的,例如,

$ touch _ast.py 
$ python -c 'from _ast import *; print(dir())' 
['AST', 'Add', 'And', 'Assert', 'Assign', 'Attribute ... 

但这因为领先_,但这_ast是一个内置的模块。 sys模块也会发生类似的情况。

$ touch sys.py 
$ python -c 'from sys import *; print(dir())' 
['__builtins__', '__doc__', '__name__', '__package__', 'api_version', 'argv', ... 

在Python _astast是单独的模块。有一条线

from _ast import * 

内置ast.py,所以进口ast也将会把一切从_ast模块,这使您误以为_astast具有相同的内容,but actually _ast is a lower level module of ast

+0

但这里发生了一些不同的事情。导入ast导入本地导入,导入_ast导入全局导入。 – 2010-06-21 07:53:16

2

这是因为_ast的模块。这里没有魔法。另外,_ast是一个内置模块(即,不作为单独文件存在但在解释器本身中编译的模块),所以它始终被加载并创建一个相同的文件不会摆脱它。

为什么_ast不会被一个文件超载的原因是,一旦一个模块被加载,python不会再在文件看起来。您可以在sys.modules中找到当前加载的所有模块的列表。如果你想要一个关于模块的完整文档,请看python文档。一切都是指定的,像这里:http://docs.python.org/tutorial/modules.html或在这里:http://docs.python.org/reference/simple_stmts.html#the-import-statement

相关问题