在 Java 中,使用 close()
方法通过移除作用域外的对象来释放资源。我对什么是 Python 等价物感到困惑?
- Python 的垃圾收集器会自动执行此操作吗?
- 是
del
方法吗? - 我应该使用
with
语句吗?
我们将不胜感激。
编辑:我的目标是在需要时明确删除类对象,而不是文件对象。
最佳答案
Should I use the with statement?
是的,根据 the documentation :
It is good practice to use the with keyword when dealing with file objects. 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:
关于java - Java 中 close() 的 Python 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38745269/