多语言展示
当前在线:245今日阅读:167今日分享:16

Python类的析构方法和call方法

Python类的析构方法和call方法
工具/原料

Python3

方法/步骤
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方法解释器销毁内存,调用析构方法

4

F5运行程序,报错信息如下:Traceback (most recent call last):  File 'C:/Program Files/Python37/destroy.py', line 13, in     ob1()TypeError: 'Ob' object is not callablenot 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方法解释器销毁内存,调用析构方法

推荐信息