1、打开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
2、F5运行程序,程序执行del ob1 析构函数被调用执行someM方法解释器销毁内存,调用析构方法
3、改写代码,测试call方法class Ob(object): def __init__(self): pass def __del__(self): print ('解释器销毁内存,调用析构方法') def someM(self): print ('执行someM方法') ob1 = Ob()ob1.someM()ob1()del ob1
4、F5运行程序,报错信息如下:Traceback (most recent call last): File "C:/Program Files/Python37/destroy.py", line 13, in <module> ob1()TypeError: 'Ob' object is not callablenot callable就是通过对象后加小括号的方法,调用的call方法,因为没有定义,所以报错
5、定义__call__方法,完整代码如下:class O水瑞侮瑜b(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
6、F5运行程序,call方法被正常调用,这是python有的call方法。执行someM方法调用了call方法解释器销毁内存,调用析构方法