在启动Python解释器后,就可以直接使用一些函数,如:
abs(-2)
Out[11]: 2
max([1,2,3,4])
Out[12]: 4
这些函数称为内建函数,在__builtins__模块中,Python在启动时就直接为我们导入了。准确的说,Python在启动时会首先加载内建名称空间,内建名称空间中有许多名字到对象之间的映射,这些名字就是内建函数的名称,对象就是这些内建函数对象。
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
可以看到有一个__builtins__的模块名称。其中包含了大量内置函数:
dir(__builtins__)
Out[14]:
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'BlockingIOError',
'BrokenPipeError',
'BufferError',
...
]
而我们在控制台直接输入__builtins__时(Python2)会出现__builtin__:
>>> __builtins__
<module '__builtin__' (built-in)>
_builtins__与__builtin__的区别
两者有何区别,以及为何这么做,请阅读以下两篇博客:
- What's the deal with __builtins__ vs __builtin__
- 理解Python中的__builtin__和__builtins__
总的概括而言:
By default, when in the__main__module,__builtins__is the built-in module__builtin__(note: no 's'); when in any other module,__builtins__is an alias for the dictionary of the__builtin__module itself.
举例如下:
1、 编写一个a.py文件,并运行
import __builtin__
print "In a"
print "__name__ is:", __name__
print "__builtin__ is __builtins__:", __builtin__ is __builtins__
print "type(__builtin__):", type(__builtin__)
print "type(__builtins__):", type(__builtins__)
$ python a.py
In a
__name__ is: __main__
__builtin__ is __builtins__: True
type(__builtin__): <type 'module'>
type(__builtins__): <type 'module'>
2、如果不在__main__module,比如在b.py中导入a.py,情况就变了:
# b.py:
import __builtin__
print "In b, before importing a"
# the output from this should be the same as when we ran
# $ python a.py
print "__name__ is:", __name__
print "__builtin__ is __builtins__:", __builtin__ is __builtins__
print "type(__builtin__):", type(__builtin__)
print "type(__builtins__):", type(__builtins__)
print "n"
import a
# code from a will execute here
$ python b.py
In b, before importing a
__name__ is: __main__
__builtin__ is __builtins__: True
type(__builtin__): <type 'module'>
type(__builtins__): <type 'module'>
In a
__name__ is: a
__builtin__ is __builtins__: False
type(__builtin__): <type 'module'>
type(__builtins__): <type 'dict'> # 变成了dict类型
CPython implementation detail: Users should not touch__builtins__; it is strictly an implementation detail. Users wanting to override values in the builtins namespace shouldimportthe__builtin__(no 's') module and modify its attributes appropriately. The namespace for a module is automatically created the first time a module is imported. 注意: Note that in Python3, the module__builtin__has been renamed tobuiltinsto avoid some of this confusion.

被折叠的 条评论
为什么被折叠?



