2025-09-10:仓库迁移
This commit is contained in:
26
8.类与对象/2.自定义字符串的输出格式.py
Normal file
26
8.类与对象/2.自定义字符串的输出格式.py
Normal file
@@ -0,0 +1,26 @@
|
||||
_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)
|
||||
|
Reference in New Issue
Block a user