python面向对象之内置函数.__str__,__repr__,__del__
#__str__打印对象使不返回对象内存地址,返回指定内容 class Student: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex def __str__(self): return '{name:%s,age:%s,sex:%s}'%(self.name,self.age,self.sex) s1 = Student('ryan',18,'male') print(s1) #{name:ryan,age:18,sex:male}
__repr__,作用同__str__,若两者都存在,则执行__str__:
class Student: def __init__(self,name,age): self.name = name self.age = age def __repr__(self): print('__repr__') return self.name def __str__(self): print('__str__') return self.name s1 = Student('ryan',12) print(s1) #__str__ #ryan
__del__,删除操作系统调用的资源,如果不执行del操作,会在程序执行完,自动调用__del__,如果执行del操作,会立刻关闭掉被调用的资源
class OpenFile: def __init__(self,filename): self.filename = filename def __del__(self): print('删除操作系统相关资源...') f1 = OpenFile('a.py') print('is success?')
#is success?
#删除操作系统相关资源...
posted on 2020-09-01 22:49 Hello_Thanos 阅读(133) 评论(0) 编辑 收藏 举报