September 1, 2019 custom 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)

>>>>

by aaa
209 912
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 notformat_spec or format_spec Not  in format_spec: # If the format_spec is empty or not in the dictionary format 
            format_spec = ' YMD ' 
        FM = format_dic [format_spec] # is selected by the dictionary 
        return fm.format (Self) 


D1 = a Date (2099,1 , 2 ) 
ZZ = the format (D1, ' YMD ' ) 
WW = the format (D1, ' MDY ' )
 Print (ZZ)
 Print (WW)

》》》》

format executed
with format
2099: 1: 2
1-2-2099

Guess you like

Origin www.cnblogs.com/python1988/p/11442406.html