python - Python 如何处理来自 "elsewhere"的对象

标签 python object memory import

这可能是一个愚蠢的问题,但我不明白 Python 如何使用我们没有定义或导入的对象。

考虑以下示例,使用 Python 的 datetime模块:

from datetime import date

date1 = date(2019,1,1)
date2 = date(2019,1,5)

type(date2-date1) #<class 'datetime.timedelta'>
type(date2)       #<class 'datetime.date'>

然后 date2-date1 属于 timedelta 类,即使我们没有导入它。

(我可能还可以编写其他示例,在这些示例中我们获取对象,即使我们没有定义它们。)

这怎么可能?

我是否应该考虑这些新对象,它们只是作为内存中的片段弹出,由其他函数返回,即使我们没有定义它们,它们“本身”包含足够的信息,以便 Python 解释器可以对它们有意义地应用 type() 和其他函数?

最佳答案

您错误地假设 import 限制了加载到内存中的内容。 import 限制在您的模块全局变量中绑定(bind)的名称

整个模块仍在加载,该模块的依赖项也是如此。仅仅因为您的命名空间 没有绑定(bind)对datetime.timedelta 对象的引用并不意味着它对datetime 模块不可用。

参见 import statement documentation :

The from form uses a slightly more complex process:

  1. find the module specified in the from clause, loading and initializing it if necessary;
  2. for each of the identifiers specified in the import clauses:
    1. check if the imported module has an attribute by that name
    2. if not, attempt to import a submodule with that name and then check the imported module again for that attribute
    3. if the attribute is not found, ImportError is raised.
    4. otherwise, a reference to that value is stored in the local namespace, using the name in the as clause if it is present, otherwise using the attribute name

因此模块的加载和初始化是一个单独的步骤,每个模块执行一次。第二步绑定(bind) namespace 中的名称。

from datetime import date 确保加载了 datetime 模块,然后找到 datetime.date 并添加 date = datetime。 date您的 命名空间。

如果您想查看加载了哪些模块,请查看 sys.modules mapping .这就是 import statement machinery checks 的位置查看给定模块是否已加载。

关于python - Python 如何处理来自 "elsewhere"的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54578327/

相关文章:

python - numpy 1.6.1 argsort() 奇怪的行为?

python - 在 reshape 图像阵列时感到困惑

python - 端口已被使用

javascript - 数组转换嵌套对象

python - 如何使用更少的内存完成文本分类任务

C++,静态检测具有不同地址的基类?

selenium - 为什么Selenium占用大量内存

python - 删除短输入函数中的多余行

javascript - 在函数中使用参数对象

c++ - 在函数内访问调用成员函数的对象