python学习-70 自定制format
# 自定义format dic_date = { 'ymd':'{0.year}:{0.month}:{0.day}', 'dmy':'{0.day}-{0.month}-{0.year}' } class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day def __format__(self, format_spec): print('--->format_spec') if not format_spec or format_spec not in dic_date: print('please enter true time type') format_spec='ymd' # 默认ymd格式的 dd=dic_date[format_spec] return dd.format(self) d1=Date(2019,11,11) print(format(d1,'ymd')) print(format(d1,'dmy')) print(format(d1,'d-m-y')) print(format(d1,'y.m.d'))
运行结果:
--->format_spec 2019:11:11 --->format_spec 11-11-2019 --->format_spec please enter true time type 2019:11:11 --->format_spec please enter true time type 2019:11:11 Process finished with exit code 0