27 lines
621 B
Python
27 lines
621 B
Python
_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)
|
|
|