attributeerror: __enter_____builtins__ 与 __builtin__(builtins)

55c1616dcbd611ecffc6c7b9191cc7ba.png

在启动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 should import the __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 to builtins to avoid some of this confusion.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值