一: __str__() 和 __repr__() 保留方法:
1 class DemoClass: 2 def __init__(self,name,age): 3 self.name = name 4 self.age = age 5 6 def __str__(self): 7 #print()-->调它 8 return "Name:{},Age:{}".format(self.name,self.age) 9 10 11 if __name__ == "__main__": 12 demo = DemoClass("tom",18) 13 print(demo) #此时调用的是demo.__str__() 14 #如果不重写__str__() 输出的就是 <__main__.DemoClass object at 0x00000238B1D6FBE0> 15 ''' 16 输出: 17 Name:tom,Age:18 18 '''
__repr__() 保留方法是个备胎:
1 class DemoClass: 2 def __init__(self,name,age): 3 self.name = name 4 self.age = age 5 6 def __repr__(self): 7 #print()-->调它 8 return "Name:{},Age:{}".format(self.name,self.age) 9 10 def __str__(self): 11 return "name:{},age:{}".format(self.name,self.age) 12 13 if __name__ == "__main__": 14 demo = DemoClass("tom",18) 15 print(demo) 16 17 ''' 18 输出: 19 name:tom,age:18 20 21 结果表明,print() 的调用顺序是: 22 print()-->str()-->demo.__str__()-->demo.__repr__()
不过,__repr__() 适合在交互环境下使用! 23 '''
还有的是,这两个保留方法都要返回字符串类型。
二:自定制格式化方式__format__():
format() 实际上调的方法是__format__()
1 format_dict = { 2 'ymd': "{0.year} {0.mon} {0.day}", 3 'y:m:d': "{0.year}:{0.mon}:{0.day}", 4 'y-m-d': "{0.year}-{0.mon}-{0.day}", 5 #0 代表的是类的实例对象self 6 } 7 class DemoClass: 8 def __init__(self, year, mon, day): 9 self.year = year 10 self.mon = mon 11 self.day = day 12 13 def __format__(self, key): 14 return format_dict[key].format(self) 15 16 17 if __name__ == "__main__": 18 demo = DemoClass(2019, 8, 6) 19 print(format(demo, 'ymd')) 20 print(format(demo, 'y:m:d')) 21 print(format(demo, 'y-m-d')) 22 ''' 23 输出 24 2019 8 6 25 2019:8:6 26 2019-8-6 27 '''