在您开始讨论建议之前,让我先编写一个类似于我的案例的POC代码:
class X:
_instance=0
def _new__():
if cls._instance:
#instance already instantiated , return the same instance
return cls._instance
cls._instance=initialize_instance()
return cls._instance现在这是我的图书馆。客户端代码的工作方式如下:
var = X()
# Do some operations on var
.
.
.
#end of program我面临的问题是,当这个客户端代码结束时,库中的一个函数必须被执行(出于某些清理目的)。但是我已经尝试过close()和__del__(),它们在客户端程序结束时都不能获得控制权。理想情况下,我认为它们应该这样做,因为这样实例就会被销毁。有没有其他方法可以在不向客户端添加任何代码的情况下实现这一点?我想客户端只进行一次调用,以获得此句柄,并让库处理一切。
发布于 2014-06-27 14:26:04
您还没有删除对X的所有引用,因为您仍然拥有cls._instance引用。这就是为什么del没有被调用的原因。
您可以将客户端对象包装在上下文管理器中,然后调用您需要调用的任何内容来清理exit方法:
class Wrapper:
has_been_wrapped = False
# Use has_been_wrapped and is_first_instance to determine when
# the last reference to X is gone.
def __init__(self, *args, **kwargs):
if not self.has_been_wrapped:
self.is_first_instance = True
self.has_been_wrapped = True
else:
self.is_first_instance = False
self.var = X(*args, **kwargs)
def __enter__(self):
return self.var
def __exit__(self):
if is_first_instance:
# Do whatever you need to do to cleanup self.var here然后在任何你想使用X的地方,像这样使用它:
with Wrapper() as var:
# now you have an instance of X that will get
# cleaned up when the with statement ends.https://stackoverflow.com/questions/24444661
复制相似问题