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不知怎么记住了这个数学.即使在我们删除了整个数学包并再次导入后,cos也被删除了.

python将这些知识保存在哪里?我们能进入吗?我们能改变它吗?

推荐答案

我要说的是,这个包裹仍然被视为进口.所以再次执行import math只需重新声明名称,但使用旧内容.

您可以使用reload来确保模块再次完整,但有些python版本也需要删除sys.modules中的条目,这使得reload的使用变得多余:

import math
del math.cos
del math
sys.modules.pop("math")   # remove from loaded modules
import math
print(math.cos(0))  # 1.0

(各种python版本reloadimport之间的差异将在后续问题Should importlib.reload restore a deleted attribute in Python 3.6?中讨论)

Python-3.x相关问答推荐

背包问题-如何减少内存使用

如何在python中有效地使用多处理和pytube库来加快下载速度?

Python避免捕获特定异常

泛型类型的参数的静态类型

Strawberry FastAPI:如何调用正确的函数?

无法导入名称';核心';来自部分初始化的模块';tensorflow_datasets';(很可能是由于循环导入)

ValueError at /register/ 视图authenticate.views.register_user 未返回HttpResponse 对象.它返回 None 相反

PyQt5 中耦合滑块和拨号小部件.解决结果不一致的问题

如何获取实例化 `types.GenericAlias` 的下标类?

计算文档中所有关键字(单词和多词)出现的频率

Python (pandas) - 判断一个 df 中的值是否在另一个(不相等)df 中的任何对之间

嵌套协议的使用(协议成员也是协议)

Python 3 `str.__getitem__` 的计算复杂度是多少?

命名元组内命名元组的 Python 语法

在python中基于列表理解的条件下跳过元素

理解 Keras 的 ImageDataGenerator 类中的 `width_shift_range` 和 `height_shift_range` 参数

为什么 Django South 1.0 使用 iteritems()?

如何通过命令行将数组传递给python

混合全局/参数和名为top的函数的奇怪python行为

如何替换 Python pathlib.Path 中的子字符串?