【发布时间】:2020-04-12 14:33:06
【问题描述】:
class MyClass:
def __init__(self):
print("HEYYYYYYYYYY") # prints
file = open("really_cool_file.txt")
print("HOOOOOOOOOOOO") # does **NOT** print
self._f = file
print("WADUP!!!!!!!!!!") # does **NOT** print
print(hasattr(self, "_f"))
def __del__(self):
print("closing any open files ")
self._f.close()
my_instance = MyClass()
print("33333333333") # NEVER PRINTS
控制台输出如下:
HEYYYYYYYYYY
closing any open files
我们收到以下错误消息:
C:\Users\Sam\AppData\Local\Programs\Python\Python38-32\python.exe
H:/PYTHON_RECORD_VIDEO/dffhsrthrth.py
Traceback (most recent call last):
File "H:/PYTHON_RECORD_VIDEO/dffhsrthrth.py", line 15, in <module>
my_instance = MyClass()
File "H:/PYTHON_RECORD_VIDEO/dffhsrthrth.py", line 4, in __init__
file = open("really_cool_file.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'really_cool_file.txt'
Exception ignored in: <function MyClass.__del__ at 0x0383D1D8>
Traceback (most recent call last):
File "H:/PYTHON_RECORD_VIDEO/dffhsrthrth.py", line 12, in __del__
self._f.close()
AttributeError: 'MyClass' object has no attribute '_f'
Process finished with exit code 1
在self._f = file 发生在__init__ 内部之前调用析构函数
我不明白如何在__init__ 完成执行之前调用析构函数。
【问题讨论】:
-
小心使用
__del__;如果您的对象因解释器退出而被删除,则不保证会调用它,就像这里的情况一样。
标签: python python-3.x destructor