__str__ and __repr__
The __str__
method in Python represents the class objects as a string – it can be used for classes. The __str__
method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.
The __str__
method is called when the following functions are invoked on the object and return a string:
- print()
- str()
If we have not defined the __str__
, then it will call the __repr__
method. The __repr__
method returns a string that describes the pointer of the object by default (if the programmer does not define it).