__format__方法可以自定格式化字符串,不定义的话会执行默认格式
format(obj) 等同于--> obj.__format__
format_dic = {
'y-m-d':'{obj.year}-{obj.mon}-{obj.day}',
'd/m/y':'{obj.day}/{obj.mon}/{obj.year}'
}
class Date:
def __init__(self,year,mon,day):
self.year = year
self.mon = mon
self.day = day
def __format__(self, format_spec): #自定制格式化
if not format_spec or format_spec not in format_dic: #用于判断用于是否输入格式信息或者输入的不在格式信息字典内
format_spec = 'y-m-d' #制定默认格式
fm = format_dic[format_spec] #通过格式字典取到对应的值
return fm.format(obj = self) #'{obj.year}-{obj.mon}-{obj.day}'.format(obj) obj应是实例化对象
d = Date(2018,10,14)
x = format(d,'y-m-d')
print(x) #2018-10-14