1 format_dic = { 2 'y-m-d': '{0.year}-{0.mon}-{0.day}', 3 'y:m:d': '{0.year}:{0.mon}:{0.day}', 4 'dmy': '{0.day}{0.mon}{0.year}', 5 } 6 7 8 class Date: 9 def __init__(self, year, mon, day): 10 self.year = year 11 self.mon = mon 12 self.day = day 13 14 def __format__(self, format_spec): 15 if format_spec not in format_dic.keys() or not format_dic[format_spec]: 16 format_spec = 'y-m-d' 17 fm = format_dic[format_spec] 18 return fm.format(self) 19 20 21 d1 = Date(2020, 3, 8) 22 print(format(d1)) 23 输出: 24 2020-3-8
自己定制format方法