__str__:改变对象的字符串显示。
class People: def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def __str__(self): # print('===========>') return '<名字:%s 年龄:%s 性别:%s>' %(self.name,self.age,self.sex) obj=People('monicx',23,'male') # print(obj.__str__())#<__main__.People object at 0x0000000001E78AC8> # print(obj)#等于print(obj.__str__())<__main__.People object at 0x00000000026D8AC8> #经过定义了__str__()后变为: print(obj)#<名字:monicx 年龄:23 性别:male>
__del__
析构方法,对象在内存中被释放时,会自动解发执行该方法。
import time class People: def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def __del__(self):#对象被删除的时候会自动触发 print('__del__') obj=People('monicx',23,'male') time.sleep(2)
如查产生的对象只是python程序级别(用户级的)那么我们就没有必要定义__del__,但若产生的对象同时还会向操作系统发起调用时,即一个对象有用户级和内核级两种资源,则必须在清除该对象的同时回收系统资源,就要用到__del__。它是应用场景跟资源有关,如下所示:
class MyOpen: def __init__(self,filepath,mode='r',encoding='utf-8'): self.filepath=filepath self.mode=mode self.encoding=encoding self.fobj=open(filepath,mode=mode,encoding=encoding) def __str__(self): msg=''' filepath:%s mode:%s encoding:%s '''%(self.filepath,self.mode,self.encoding) return msg def __del__(self): #回收应用资源时先回收系统的资源。 self.fobj.close() f=MyOpen('test.py')#f.是python的变量会被回收。 print(f.fobj) res=f.fobj.read() print(res)