format_dic = {
"ymd":"{0.year} {0.month} {0.day}",
"y:m:d":"{0.year}:{0.month}:{0.day}",
"y-m-d":"{0.year}-{0.month}-{0.day}"
}
class MyDate:
def __init__(self,year,month,day):
self.year = year;
self.month = month;
self.day = day;
def __format__(self,format_spec):
print("我执行了...%s"%format_spec)
if not format_spec or format_spec not in format_dic:
format_spec = "ymd"
sf = format_dic.get(format_spec)
return sf.format(self)
d = MyDate(2019,4,8)
print(format(d,'y:m:d')) # format() 会调用 对象d的__format__函数