接上一篇,内置方法续集:
六、__str__,__repr__ 和 __format__
1、作用:__str__,__repr__ 改变对象的字符串显示
__format__ 自定制格式化字符串
2、示例:
#!/usr/bin/env python3 #-*- coding:utf-8 -*- # write by congcong format_dict={ 'way1':'{obj.name}-{obj.addr}-{obj.type}',#学校名-学校地址-学校类型 'way2':'{obj.type}:{obj.name}:{obj.addr}',#学校类型:学校名:学校地址 'way3':'{obj.type}/{obj.addr}/{obj.name}',#学校类型/学校地址/学校名 } class School: def __init__(self,name,addr,type): self.name = name self.addr = addr self.type = type def __repr__(self): return 'School(%s,%s)'%(self.name,self.addr) def __str__(self): return '(%s,%s)'%(self.name,self.addr) def __format__(self, format_spec): if not format_spec or format_spec not in format_dict: format_spec = 'way1' fmt =format_dict[format_spec] return fmt.format(obj=self) s1 = School('lufei','上海','培训机构') print('from repr:',repr(s1)) # from repr: School(lufei,上海) print('from str:',str(s1)) # from str: (lufei,上海) print(s1) # (lufei,上海) print(format(s1,'way2'))# 培训机构:lufei:上海 print(format(s1,'way3')) # 培训机构/上海/lufei print(format(s1,'abcdef')) # 培训机构/上海/lufei ''' str函数或者print函数--->obj.__str__() repr或者交互式解释器--->obj.__repr__() 如果__str__没有被定义,那么就会使用__repr__来代替输出 '''