str (), and repr () both are used to get string representation of the object. They are called special (dunder) methods.
__str__ (or) str ()
__repr__ (or) repr ()
Above code repr () represents the official string representation, but str () is a readable format.
Difference between str() and repr()
goal of __str__ is to be readable.
str () is used for creating output for end user in readable format.
goal of __repr__ is to be unambiguous.
repr () is mainly used for debugging and development.
__repr__ () is the fallback method to __str__()
if str () not implemented, in the class, then it will call the repr() method.
Above code print(emp1) calls emp1.__repr__()
Above code print(emp1) calls emp1.__str__()
check the following code to call both repr() and str()
repr(emp1) or emp1.__repr()
str(emp1) or emp1.__str()
A user defined class should have __repr__ () method, if we need detailed information for debugging purposes. A class should have __str__ () method also to get readable text from object.
Comments