Abh*_*ngh 4 python garbage-collection dispose idisposable
我必须为 C API 创建一个 python 包装器。我曾经ctypes
从 python 调用 C dll。我能够创建 Handle 并从 python 使用它。我正在寻找类似于 C# 的 Python 中的 Dispose 模式。python 中是否存在 Dispose 模式?
Python 有:
try ... finally
,相当于C#中的类似构造;with
语句类似于using(... = new ...())
C# 中的 。请注意,与 C# 不同,with
statement 接受已构造的对象,__enter__
在进入和__exit__
退出时调用。即,对象在 中初始化__init__
,资源在 中获取__enter__
并释放__exit__
。因此,这样的对象可以多次使用。
有了contextlib.closing
,就有可能更接近 C#。在方法中获取资源__init__
并处理它close
。contextlib.closing
制作一个包装器,调用close
其__exit__
.
对于您的情况,您应该在 中做好所有准备__init__
,在 中获取实际句柄__enter__
,并在 中处理它__exit__
。