八 __str__,__repr__,__format__
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age
# 相当于java的toString()
def __str__(self):
return ('name:%s,age:%s'%(self.name,self.age))
def __repr__(self):
return ('name1:%s,age1:%s'%(self.name,self.age))
f = Foo('long',20)
print(f) # f.__str__()
print(f) # f.__repr__()
# 如果__str__没有被定义,那么就会使用__repr__来代替输出
# 注意:这俩方法的返回值必须是字符串,否则抛出异常
__format__ 自定义格式化
format_dict = {
'ymd':'{0.year}{0.month}{0.day}',
'y-m-d':'{0.year}-{0.month}-{0.day}'
}
class Date:
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec):
print('执行了__format__:',format_spec)
if not format_spec or format_spec not in format_dict:
format_spec = 'ymd'
fm = format_dict[format_spec]
return fm.format(self) # '{0.year}{0.month}{0.day}'.format(d1) # 2019822
d1 = Date(2019,8,22)
x = format(d1,'y-m-d') # d1__format__()
print(x) # 2019-8-22
# x = '{0.year}{0.month}{0.day}'.format(d1) # 2019822
# print(x)