python - __builtin__ 如何在运行时可用?

标签 python

为什么第一条语句返回NameError,而max可用

>>> __builtin__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__builtin__' is not defined
>>> max
<built-in function max>
>>> import __builtin__
>>> __builtin__.max
<built-in function max>

最佳答案

The builtins namespace associated with the execution of a code block is actually found by looking up the name __builtins__ in its global namespace; this should be a dictionary or a module (in the latter case the module’s dictionary is used). 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. __builtins__ can be set to a user-created dictionary to create a weak form of restricted execution.

所以它实际上是在查找 __builtins__(因为你在主模块中)

>>> __builtins__.max
<built-in function max>

但如上所述,这只是 __builtin__ 的别名(它不是主模块命名空间的一部分,尽管它已被 __builtins__ 加载和引用).

关于python - __builtin__ 如何在运行时可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16252457/

相关文章:

python - 将 MySQL Connector 与 Python 结合使用时出现 SSL 连接错误

python - Matplotlib:用户定义的绘图函数打印两次

python - 执行任务后在 Python 中实现自动保存功能

python - 更新记事本选项卡上的时钟

python - SQLAlchemy 如何为同一个表定义两个模型

python - 使用 matplotlib 在另一个轴中嵌入多个插入轴

python - 如何在Python中使用模板库

python - ndb.TextProperty 到 ndb.StringProperty

python - 逆转 Python 的 re.escape

python - 在Python中增量计算大数组的汇总统计