Files
Python_CookBook_repo/8.类与对象/2.自定义字符串的输出格式.py

27 lines
621 B
Python
Raw Permalink Normal View History

2025-09-10 16:12:45 +08:00
_formats = {
'ymd': '{d.year}-{d.month}-{d.day}',
'mdy': '{d.month}-{d.day}-{d.year}',
'dym': '{d.day}-{d.month}-{d.year}'
}
# 通过重写类的__format__方法,我们可以让类在被填充的时候变成任何样子
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(2024, 11, 11)
format(d)
format(d, 'mdy')
"The Date is {:ymd}".format(d)
"The Date is {:dym}".format(d)