Python 中有 Dispose 模式吗?

Abh*_*ngh 4 python garbage-collection dispose idisposable

我必须为 C API 创建一个 python 包装器。我曾经ctypes从 python 调用 C dll。我能够创建 Handle 并从 python 使用它。我正在寻找类似于 C# 的 Python 中的 Dispose 模式。python 中是否存在 Dispose 模式?

Geo*_*tov 7

Python 有:

  • try ... finally,相当于C#中的类似构造;
  • with语句类似于using(... = new ...())C# 中的 。

请注意,与 C# 不同,withstatement 接受已构造的对象,__enter__在进入和__exit__退出时调用。即,对象在 中初始化__init__,资源在 中获取__enter__并释放__exit__。因此,这样的对象可以多次使用。

有了contextlib.closing,就有可能更接近 C#。在方法中获取资源__init__并处理它closecontextlib.closing制作一个包装器,调用close__exit__.

对于您的情况,您应该在 中做好所有准备__init__,在 中获取实际句柄__enter__,并在 中处理它__exit__