8.2 我们想通过对象的format函数的字符串方法来支持自定义的格式输出
>>> _formats = { 'ymd':'{d.year}-{d.month}-{d.day}','mdy':'{d.month}/{d.day}/{d.year}'}
>>> class Date:
... def __init__(self,year,month,day):
... self.year = year
... self.month = month
... self.day = day
... def __format__(self,code):
... if code=="":
... code = "ymd"
... fmt = _formats[code]
... return fmt.format(d=self)
>>> d = Date(2022,5,27)
>>> format(d)
'2022-5-27'
>>> format(d,'mdy')
'5/27/2022'
>>> 'the date is :{:ymd}'.format(d)
'the date is :2022-5-27'
>>> 'the date is :{:mdy}'.format(d)
'the date is :5/27/2022'
>>>
>>> d.__format__("ymd")
'2022-5-27'
>>> d.__format__("mdy")
'5/27/2022'
>>>
网友评论