Python3
打开Python开发工具IDLE,新建‘destroy’并写代码如下:class Ob(object): def __init__(self): pass def __del__(self): print ('解释器销毁内存,调用析构方法') def someM(self): print ('执行someM方法') ob1 = Ob()ob1.someM()del ob1析构函数__del__当对象引用计数为0是解释器自动调用,显示调用的方法是del object
F5运行程序,程序执行del ob1 析构函数被调用执行someM方法解释器销毁内存,调用析构方法
F5运行程序,报错信息如下:Traceback (most recent call last): File 'C:/Program Files/Python37/destroy.py', line 13, in
定义__call__方法,完整代码如下:class Ob(object): def __init__(self): pass def __del__(self): print ('解释器销毁内存,调用析构方法') def someM(self): print ('执行someM方法') def __call__(self): print ('调用了call方法') ob1 = Ob()ob1.someM()ob1()del ob1
F5运行程序,call方法被正常调用,这是python有的call方法。执行someM方法调用了call方法解释器销毁内存,调用析构方法