Python如何处理来自“别处”的对象

2024-04-26 13:53:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能是一个愚蠢的问题,但我不懂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()和其他函数应用于它们?你知道吗


Tags: 模块对象函数fromimport示例datetimedate
2条回答
from datetime import date

Date正在某处导入timedelta,因为它可能是一个依赖项,即使您看不到它。你知道吗

您错误地认为import限制了加载到内存中的内容。import限制模块全局变量中绑定的名称。你知道吗

整个模块仍然处于加载状态,该模块的依赖项也处于加载状态。仅仅因为您的名称空间没有绑定对datetime.timedelta对象的引用并不意味着它对datetime模块不可用。你知道吗

参见^{} 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

因此,模块的加载和初始化是一个单独的步骤,每个模块执行一次。第二步绑定命名空间中的名称。你知道吗

from datetime import date确保datetime模块已加载,然后找到datetime.date,并将date = datetime.date添加到您的命名空间中。你知道吗

如果您想查看加载了哪些模块,请查看^{} mapping。这就是^{} statement machinery checks用来查看给定模块是否已加载的位置。你知道吗

相关问题 更多 >