Justin-刘清政的博客

python/面向对象高阶/7-__format__

2020-12-21

一、format

  • 自定制格式化字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
date_dic = {
'ymd': '{0.year}:{0.month}:{0.day}',
'dmy': '{0.day}/{0.month}/{0.year}',
'mdy': '{0.month}-{0.day}-{0.year}',
}


class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day

def __format__(self, format_spec):
# 默认打印ymd的{0.year}:{0.month}:{0.day}格式
if not format_spec or format_spec not in date_dic:
format_spec = 'ymd'
fmt = date_dic[format_spec]
return fmt.format(self)


d1 = Date(2016, 12, 29)
1
print(format(d1))
1
2016:12:29
1
print('{:mdy}'.format(d1))
1
12-29-2016
使用支付宝打赏
使用微信打赏

点击上方按钮,请我喝杯咖啡!

扫描二维码,分享此文章