SUMMARY __ __str customize the output () and __repr __ () and __format __ () using

A: __str __ () and __repr __ () Retention method:

 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) # At this time the call is Demo .__ STR __ ()  
 14      # If no override __str __ (output is <__ main __ DemoClass Object AT 0x00000238B1D6FBE0.>) 
15  '' ' 
16      output:
 . 17      the Name: Tom, Age: 18 is
 18 is  ' ''

 

__repr __ () method is to retain a spare tire:

 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 is )
 15      Print (Demo)
 16      
. 17  '' ' 
18 is      output:
 . 19      name: Tom, Age: 18 is
 20 is      
21 is      the results show, print () call sequence is:
 22 is      Print () -> str () - > demo .__ str __ () -> demo .__ repr __ () 
    However, __ repr __ () suitable for use in an interactive environment!
23 '' '

Still, these two methods should retain the return string type.

Two: __ custom formatting way __format () :

format () method is actually transferred __format __ () 

. 1 format_dict = {
 2      ' YMD ' : " {} {0.mon 0.year 0.day} {} " ,
 . 3      ' Y: m: D ' : " {} 0.year: 0.mon {}: { } 0.day " ,
 . 4      ' YMD ' : " {} 0.year - 0.mon} {-} {0.day " ,
 . 5      # 0 represents the self class instance object 
. 6  }
 . 7  class DemoClass:
 . 8      DEF  the __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      output      
 24      2019 8. 6
 25      : 2019 8: 6
 26 is      2019-8-6
 27  '' '

 

Guess you like

Origin www.cnblogs.com/zach0812/p/11310823.html