python的单实例类如何析构
class myTestClass(object):
__Inst=None
def __new__(self):
if self.__Inst is None:
self.__Inst=object.__new__(self)
return self.__Inst
def __del__(self)
print('object has been destroyed')
if __name__=='__main__':
Inst=myTestClass()
为什么析构函数不被调用呢?如何才能调用? 我主动的 del Inst也不行
[解决办法]
非要自动的话,试试下面方式:
def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance
@singleton
class myTestClass(object):
def __del__(self):
print('object has been destroyed')
if __name__=='__main__':
Inst=myTestClass()
import atexit
class myTestClass(object):
__Inst=None
def __new__(cls):
if cls.__Inst is None:
cls.__Inst=object.__new__(cls)
atexit.register(cls.__del__, cls.__Inst)
return cls.__Inst
def __del__(self):
print('object has been destroyed')
if __name__=='__main__':
Inst=myTestClass()