我有一个打开文件进行写入的类。在我的析构函数,我调用关闭该文件的函数:del MyClass不会调用object .__ del __()
class MyClass:
def __del__(self):
self.close()
def close(self):
if self.__fileHandle__ is not None:
self.__fileHandle__.close()
但是当我喜欢的代码删除对象:
myobj = MyClass()
myobj.open()
del myobj
,如果我尝试重新实例化对象,我得到一个数值错误:
ValueError: The file 'filename' is already opened. Please close it before reopening in write mode.
,而如果我叫myobj.close()
del myobj
之前,我不明白这个问题。那么为什么__del__()
没有被叫?
尝试从'对象'继承 - 不这样做已经被认为是过时的风格约六年。 – Marcin 2012-01-18 09:37:10
你应该展示更多的代码。怎么能告诉你'myobj.close()'如何改变,而不知道它是干什么的? – ugoren 2012-01-18 09:37:49
请记住'del'不会调用__del__'。它只是删除了其中一个参考。通常最好是明确关闭,可能使用上下文管理器协议('with'语句)。 – yak 2012-01-18 09:45:50