1. See the difference First
1 classTest (object):2 def __init__(Self, value='Hello, world!.'):3Self.data =value4 5>>> T =Test ()6>>>T7<__main__. Test at 0x7fa91c307190>8>>>PrintT9<__main__. Test Object at 0x7fa91c307190>Ten One #did you see that? The above-printed class object is not very friendly and shows the memory address of the object A #let's reconstruct the __repr__ and __str__ of the class, and see what the difference is between the two. - - #Refactoring __repr__ the classTestrepr (Test): - def __repr__(self): - return 'Testrepr (%s)'%Self.data - +>>> TR =Testrepr () ->>>TR + testrepr (Hello, world!) A>>>PrintTR at testrepr (Hello, world!) - - #after refactoring the __repr__ method, the information printed either directly or through print is displayed in the format defined in our __repr__ method. - - #Refactoring __str__ - calss teststr (Test): in def __str__(self): - return '[Value:%s]'%Self.data to +>>> ts =teststr () ->>>TS the<__main__. Teststr at 0x7fa91c314e50> *>>>PrintTS $ [Value:hello, world!]Panax Notoginseng - #you will find that the direct output of the TS is not output in the format defined in our __str__ method, and the print output changes the
View Code
Both __repr__ and __str__ are for display, __str__ is user-oriented, and __repr__ is for programmers.
The print operation will first attempt the __str__ and STR built-in functions (the internal equivalent form of the print run), which should normally return a friendly display.
__REPR__ is used in all other environments: Prompt response in interactive mode and repr function, print and STR are used if __str__ is not used. It should usually return an encoded string that can be used to recreate the object, or to give the developer a detailed display.
We can reconstruct the __repr__ method when we want to display it uniformly in all environments, and when we want to support different displays in different environments, such as end-user display using __STR__, while programmers use the underlying __repr__ to display during development, actually __str__ just covers the __repr__ to get a more user-friendly display.
__repr__ and __str__ differences in Python