python 自定义字符串的输出格式

2022-05-26  本文已影响0人  孙广宁
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'
>>>
上一篇 下一篇

猜你喜欢

热点阅读