2019年9月1日 定制format

x='{0}{0}{0}'.format('a')
print(x)

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


d1=Date(2099,1,2)
y='{0.year}{0.mon}{0.day}'.format(d1)
z='{0.year}-{0.mon}-{0.day}'.format(d1)
print(y)
print(z)

>>>>

aaa
209912
2099-1-2

format_dic={
    'ymd':"{0.year}:{0.mon}:{0.day}",
    'm-d-y':'{0.mon}-{0.day}-{0.year}',
}

class Date:
    def __init__(self,year,mon,day):
        self.year=year
        self.mon=mon
        self.day=day
    def __format__(self, format_spec):
        print('format 执行')
        if not format_spec or format_spec not in format_spec: #如果 format_spec为空,或者不在字典的格式内
            format_spec='ymd'
        fm=format_dic[format_spec]#通过字典来进行选择
        return fm.format(self)


d1=Date(2099,1,2)
zz=format(d1,'ymd')
ww=format(d1,'m-d-y')
print(zz)
print(ww)

》》》》

format 执行
format 执行
2099:1:2
1-2-2099

猜你喜欢

转载自www.cnblogs.com/python1988/p/11442406.html