#自定义格式
x = '{0}{0}{0}'.format('dog')
print(x)
class Date:
def __init__(self,year, mon,day):
self.year = year
self.mon = mon
self.day = day
d1 = Date(2016,12,14)
x = '{0.year}{0.mon}{0.day}'.format(d1)
y = '{0.year}:{0.mon}:{0.day}'.format(d1)
z = '{0.year}-{0.mon}-{0.day}'.format(d1)
print(x)
print(y)
print(z)
#定制Format
#利用字典定义所需的格式
format_dic ={
'ymd':'{0.year} {0.mon} {0.day}',
'm-d-y':'{0.mon}-{0.day}-{0.year}',
'y:m:d':'{0.year}:{0.mon}:{0.day}'
}
class Date:
def __init__(self,year, mon,day):
self.year = year
self.mon = mon
self.day = day
def __format__(self,format_sepc):
print('我执行了')
print('-->',format_sepc)
#判断没有输入格式以及输入格式不在字典范围内,使用默认格式
if not format_sepc or format_sepc not in format_dic:
format_sepc='ymd'
fm = format_dic[format_sepc]
#返回格式化好后的日期
return fm.format(self)
d2 = Date(2016,12,14)
format(d2)
print(format(d2, 'ymd'))
print(format(d2, 'm-d-y'))
print(format(d2, 'm:d-y'))