gpt4 book ai didi

python - 包上的 `del` 有某种内存

转载 作者:IT老高 更新时间:2023-10-28 20:39:01 25 4
gpt4 key购买 nike

del 似乎有一些让我困惑的内存。请参阅以下内容:

In [1]: import math

In [2]: math.cos(0)
Out[2]: 1.0

In [3]: del math.cos

In [4]: math.cos(0)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-9cdcc157d079> in <module>()
----> 1 math.cos(0)

AttributeError: module 'math' has no attribute 'cos'

很好。让我们看看如果我们删除整个数学包会发生什么:

In [5]: del math

In [6]: math.cos(0)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-9cdcc157d079> in <module>()
----> 1 math.cos(0)

NameError: name 'math' is not defined

所以现在数学本身已经消失了,正如预期的那样。

现在让我们再次导入数学:

In [7]: import math

In [8]: math.cos(0)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-9cdcc157d079> in <module>()
----> 1 math.cos(0)

AttributeError: module 'math' has no attribute 'cos'

所以不知何故,交互式 python 记得即使在我们删除整个数学包并再次导入之后,math.cos 也被专门删除了。

python 将这些知识保存在哪里?我们可以访问它吗?我们可以改变它吗?

最佳答案

一个包只从磁盘读取一次,然后作为可变单例存储在内存中。第二次导入它时,您会得到与之前导入的完全相同的单例,但它仍然缺少它的 cosdel math 只是删除它的本地名称,它不会从 Python 整体“取消导入”包。

关于python - 包上的 `del` 有某种内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48809458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com