简体   繁体   English

Java中的close()相当于什么?

[英]What is the Python equivalent of close() in Java?

In Java, using the close() method frees resources by removing out of scope objects. 在Java中,使用close()方法通过删除范围外对象来释放资源。 I am confused as to what is the Python equivalent for this? 我很困惑Python的等价物是什么?

  • Does Python's garbage collector automatically do this? Python的垃圾收集器会自动执行此操作吗?
  • Is it the del method? del方法吗?
  • Should I use the with statement? 我应该使用with声明吗?

Any help will be appreciated. 任何帮助将不胜感激。

Edit: My goal is to explicitly remove class objects when desired, not file objects. 编辑:我的目标是在需要时显式删除类对象 ,而不是文件对象。

Should I use the with statement? 我应该使用with声明吗?

Yes, according to the documentation : 是的,根据文件

It is good practice to use the with keyword when dealing with file objects. 在处理文件对象时,最好使用with关键字。 This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. 这样做的好处是,即使在路上引发异常,文件也会在套件完成后正确关闭。 It is also much shorter than writing equivalent try-finally blocks: 它也比编写等效的try-finally块短得多:

你会在这里找到你的答案:在你的代码之前放置gc.collect()。

ICart's comment is spot on for many different situations. ICart的评论适用于许多不同的情况。 However, regarding the creation and disposal of objects in general, I think this other thread provides a pretty good explanation of how python handles their objects (reference counts), and where garbage collection comes in. 但是,关于一般的对象的创建和处理,我认为这个其他线程提供了一个很好的解释python如何处理它们的对象(引用计数),以及垃圾收集的来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM