Skip to main content
 首页 » 编程设计

python之在 python 中恢复所有内置名称

2024年10月01日8cloudgamer

看完之后 How do I clear all variables in the middle of a Python script?我使用了代码:

import sys 
sys.modules[__name__].__dict__.clear() 

它删除了 python 中的所有内置名称。

我试图通过卸载我的 Anaconda 并重新安装来恢复它,但似乎无法解决问题。

例如对于我的代码:

ax.plot_surface(x1data2d , x2data2d , ydata2d, cmap=cm.coolwarm, 
                       linewidth=0, antialiased=False) 

显示错误:

NameError: name 'cm' is not defined 

有谁知道如何恢复这些内置名称?

请您参考如下方法:

cm 不是内置名称。

要使您的代码正常工作,您必须导入 cm模块:

from matplotlib import cm 

请注意,sys.modules[__name__].__dict__.clear()(几乎)总是一个坏主意。如果你不想用很多变量弄乱你的“命名空间”,你最好使用 modules并避免任何 from some_package import * 语句。

请注意,您不必在 sys.modules[__name__].__dict__.clear() 之后重新安装 Python,您只需重新启动解释器即可。但请不要使用该命令 - 即使是 author of the answer说这不是他推荐的东西:

I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).