加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python如何处理来自“其他地方”的对象

发布时间:2020-12-20 11:09:32 所属栏目:Python 来源:网络整理
导读:这可能是一个愚蠢的问题,但我不知道如何使用我们没有定义或导入的对象. 请考虑以下示例,使用Python的datetime模块: from datetime import datedate1 = date(2019,1,1)date2 = date(2019,5)type(date2-date1) #class 'datetime.timedelta'type(date2) #class
这可能是一个愚蠢的问题,但我不知道如何使用我们没有定义或导入的对象.

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

from datetime import date

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

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

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

(我可能还会做其他示例,我们获取对象,即使我们没有定义它们.)

怎么会这样?

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

解决方法

您错误地认为导入限制了加载到内存中的内容. import限制模块全局变量中绑定的名称.

整个模块仍然被加载,该模块的依赖项也是如此.仅仅因为您的命名空间没有绑定对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

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

从datetime导入日期确保加载datetime模块,然后找到datetime.date并将date = datetime.date添加到命名空间.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读