How to remove the variables in python to clear ram memory in python?
R :
a = 2
rm(a)
Python:
a = 2
How to clear the single variables or a group of variables?
How to remove the variables in python to clear ram memory in python?
R :
a = 2
rm(a)
Python:
a = 2
How to clear the single variables or a group of variables?
python 内存清理由垃圾收集器管理。在 CPython 上,它基于引用计数。您可以像这样显式调用垃圾收集器:
import gc
gc.collect()
这可以在调用一个使用 ram 方面的大变量的函数之后完成。请注意,您不必显式调用此函数,因为最终将调用垃圾收集器以自动释放 ram。
如果您仍想显式删除变量,您可以使用del语句(如前所述),如下所示:
x = [1, 2, 3]
i = 42
s = 'abc'
del s # delete string
del x[1] # delete single item in a list
del x, i # delete multiple variables in one statement
为了更好地理解del
它的作用及其局限性,让我们看看 python 如何在 ram 上存储变量。
x = [1, 2, 3]
上面的代码在名称与存储在堆上x
的列表之间创建了一个引用。只是指向该列表的指针。[1, 2, 3]
x
x = [1, 2, 3]
y = x
x is y # True
x
在这个例子中,我们在堆上有引用和列表[1, 2, 3]
,但是这个新y
变量是什么?它只是另一个指针,这意味着现在我们有两个指向同一个[1, 2, 3]
列表的指针。
回到del
语句,如果我们删除一个变量,它不会影响列表或另一个变量
x = [1, 2, 3]
y = x
del x
print(y) # prints [1, 2, 3]
所以在这里我们不会释放列表,只会减少对列表的引用计数,但我们仍然y
指向它。
为了克服这个问题,我们可以使用weakref模块指向y
列表,当x
被删除时,列表也会被删除。
gc.collect()
在繁重的记忆功能后使用del x, y
删除指向特定对象的所有指针以释放它weakref
模块来避免在删除所有其他对它们的引用后将对象保留在内存上利用del
>>> a=2
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined