Article From:https://www.cnblogs.com/zhengyuan/p/9060821.html
1.First look at the difference

 1 class Test(object):
 2     def __init__(self, value='hello, world!'):
 3         self.data = value
 4 
 5 >>> t = Test()
 6 >>> t
 7 <__main__.Test at 0x7fa91c307190>
 8 >>> print t
 9 <__main__.Test object at 0x7fa91c307190>
10 
11 # Do you see it? The printed object is not very friendly, indicating the memory address of the object.
12 # Next we reconstruct the __repr__ and __str__ of the class to see what the difference between them is.
13 
14 # Refactoring __repr__
15 class TestRepr(Test):
16     def __repr__(self):
17         return 'TestRepr(%s)' % self.data
18 
19 >>> tr = TestRepr()
20 >>> tr
21 TestRepr(hello, world!)
22 >>> print tr
23 TestRepr(hello, world!)
24 
25 # After refactoring the __repr__ method, the information printed directly by the output object or by print is displayed in the format defined in our __repr__ method.
26 
27 # Refactoring __str__
28 calss TestStr(Test):
29     def __str__(self):
30         return '[Value: %s]' % self.data
31 
32 >>> ts = TestStr()
33 >>> ts
34 <__main__.TestStr at 0x7fa91c314e50>
35 >>> print ts
36 [Value: hello, world!]
37 
38 # You will find that the output of object TS directly does not output according to the format defined in our __str__ method, while the output information is changed by print.

View Code

__repr____str__ and the two methods are all used for display. __str__ is user oriented, while __repr__ is for programmers.

  • The print operation will first try __str__ and STR built-in functions (internal equivalent forms of print running), which usually should return a friendly display.

  • __repr__For all other environments: for interactive mode prompt response and repr function, without using __str__, print and str will be used. It should usually return a coded string, which can be used to recreate objects or display them in detail.

When we want to show it uniformly in all environments, we can restructure the __repr__ method; when we want to support different displays in different environments, such as the end user shows the use of __str__, the programmer uses the underlying __repr__ to display it during the development.Str__ just covers __repr__ to get a more friendly user display.

 

Leave a Reply

Your email address will not be published. Required fields are marked *