The magic methods __str__ and __repr__ are used for converting an instance object into a string. The method __str__ is invoked when an instance object is converted to a string by calling the str built-in function. It is also invoked when an instance object is printed using the print function because print implicitly calls the str built-in function. The method __repr__ is invoked by the repr built-in function, and it is also used to display the object in the interactive terminal. If __str__ is not defined, then this method is invoked for str(obj) and print(obj) also.
Both __str__ and __repr__ methods return a string representation of the instance, but __str__ is generally used for the end user of the class; it returns a human-readable and user-friendly string representation of the object. The string returned by __repr__ is a descriptive and unambiguous string representation of the object. It returns a Python-interpretable text that can be used by programmers for debugging. This text is generally a valid Python expression from which you can re-create the instance object using the eval function.
Let us see what happens when we print an instance object of our Fraction class.
>>> f = Fraction(2, 3)
>>> print(f)
<__main__.Fraction object at 0x000001C9DB23B100>
We get a string containing the class name and the object id. The interactive echo and str function will also give the same string.
标签:__,function,string,Python,object,instance,str,representation From: https://www.cnblogs.com/zhangzhihui/p/18333327