Look at the following example to get a sense of
ClassTest(object):Def__init__(Self, value=' Hello, world! '): Self.data = value>>> t = Test ()>>> t<__main__. Test at0x7fa91c307190>>>>Print t<__main__. Test Object at0x7fa91c307190># Did you see it? The above-printed class object is not very friendly and shows the memory address of the object# below we reconstruct the __repr__ and __str__ of the class, and see what the difference is between them.# refactoring __repr__ClassTestrepr(Test):Def__repr__(self):Return' Testrepr (%s) '% Self.data>>> tr = TESTREPR ()>>> trtestrepr (Hello, world!) >>> print trtestrepr (Hello, world!) # 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): def __str__return "[Value:%s] '% self.data>>> ts = teststr () >>> ts<__main__. Teststr at 0x7fa91c314e50>>>> print Ts[value:hello, world!] # you will find that the direct output of the object TS is not output in the format defined in our __str__ method, but the information printed with print changes the
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.
The __str__ and __repr__ methods in Python