python 自定义字符串的输出格式
2022-05-26 本文已影响0人
孙广宁
8.2 我们想通过对象的format函数的字符串方法来支持自定义的格式输出
- 可以再类中定义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)
- Date类的实例现在可以支持如下的格式化
>>> 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'
>>>