Python类的析构方法和call方法
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 callable
not callable就是通过对象后加小括号的方法,调用的call方法,因为没有定义,所以报错

5、定义__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

6、F5运行程序,call方法被正常调用,这是python有的call方法。
执行someM方法
调用了call方法
解释器销毁内存,调用析构方法
