本文介绍了Python 中的 __builtin__ 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个模块 Test 并且如果我需要列出其中的所有函数,我会这样做:

If I have a module Test and if I need to list all the functions in them, I do this:

import Test
dir(Test)

除非我导入模块,否则我将无法使用其中定义的函数.

Unless I import the module I won't be able to use the functions defined in them.

但是__builtin__模块中的所有函数都可以不导入使用.但是如果没有 import __builtin__,我将无法执行 dir(__builtin__).这是否意味着我们在不导入整个模块的情况下使用这些函数?

But all the functions in __builtin__ module can be used without importing. But without import __builtin__ I am not able to do a dir(__builtin__). Does that mean we use the functions without importing the entire module?

from __builtin__ import zip

是不是和上面一样?但是如果我执行del zip,我得到

Is it something like the above? But if I do del zip, I get

NameError: name 'zip' 未定义

谁能解释一下这种行为?

Can anyone please explain this behavior?

推荐答案

Python 语言文档,Python 中的名称首先在本地范围内查找,然后在任何封闭的本地范围内查找,然后在模块级范围内,最后在内置的命名空间中查找.插入所以内置函数在某种程度上是特殊的.它们不会被导入到你的模块的作用域中,但是如果在其他任何地方都找不到名称,Python 会在作用域 __builtin__ 中查找它.

As explained in the Python language docs, names in Python are resolved by first looking them up in the local scope, then in any enclosing local scope, then in the module-level scope and finally in the namespace of the built-ins. So built-ins are somehow special-cased. They are not imported in your module's scope, but if a name is not found anywhere else, Python will look it up in the scope __builtin__.

请注意,您无需导入即可访问此范围的内容.一种可移植的方法是

Note that you can access the contents of this scope without importing it. A portable way to do this is

import sys
print(dir(sys.modules["__builtin__"]))

在 CPython 中,这也有效

In CPython, this also works

print(dir(__builtins__))

但这被视为实现细节,可能不适用于其他 Python 实现或未来版本.

but this is considered an implementation detail and might not be available for other Python implementations or future versions.

这篇关于Python 中的 __builtin__ 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:14