Python如何处理后释放类对象的内存? [英] Python how to release the memory for class object after processing it?

查看:195
本文介绍了Python如何处理后释放类对象的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 None关键字删除类对象.

 class demo:
   class members

 obj= demo()
 some processing
 obj=None

通过使用,是否可以释放内存?

By using None,will the memory be released?

我发现 del 也可以用于删除类对象.或者我应该使用

I found that del can also be used to delete a class object.Or I should use

   del obj

释放内存?

使用 del和None 删除类对象和释放内存或调用垃圾回收有什么区别?

What is the difference between using del and None in deleting a class object and releasing the memory or invoking garbage collection?

推荐答案

没有更多引用时,将释放Python对象.

Python objects are released when there are no more references to the object.

obj 绑定到 None 将减少对对象的引用计数,而 del obj 也将减少.在这两种情况下,如果 obj 是对该实例的最后引用,该实例将被清除.

Rebinding obj to None would decrease the reference count to the object, and so would del obj. In both cases, the instance would be cleared if obj was the last reference to it.

然后的区别是您以后如何使用 obj .重新绑定将保留该变量(现在已绑定到 None ), del 会将其完全删除,您将得到一个 NameError .您选择的是您的选择,它不会对如何从内存中清除实例产生影响.

The difference then is how you can use obj afterwards. Rebinding retains the variable (it is now bound to None), del removes it altogether and you'd get a NameError. What you pick is your choice, it won't have influence on how the instance is cleared from memory.

这篇关于Python如何处理后释放类对象的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆