java - Java 中 close() 的 Python 等价物是什么?

标签 java python python-2.7 python-3.x resources

在 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/

相关文章:

java - 强制更新 JTable 不起作用

python - 在 Python 中将数据写入磁盘作为后台进程

python - 添加新列时在 Alembic 中设置列​​顺序

python - 即使值为 false,Django BooleanField 也始终会进行检查

pandas - 从 pandas 导出到没有行名称(索引)的_excel?

java - calc() 类型方法中的 else if 语句返回不正确的值

java - Spring Security 在 Controller 中使用@security 注释

java - 在 Java Swing 中用图案填充矩形

python - 从 python 列表创建子列表

python - IDLE shell 无法找到 cx_Oracle 的镜像(原因 : image not found)