![]() |
VOOZH | about |
The repr() function in Python is used to return a string representation of an object that can be used to recreate the object when passed to eval(). It is mainly used for debugging and logging because it provides an unambiguous representation of an object.
To understand more clearly, think of repr() as a blueprint for an object, while str() is a user-friendly description of it. Let's take an example:
Hello World 'Hello\nWorld'
Explanation:
This shows that repr() is meant for debugging and object recreation, while str() is for user-friendly display.
repr(object)
Parameters:
Return Type: repr() function returns a string (str) representation of the given object (<class 'str'>).
Using repr() function on any data-type converts it to a string object.
42 <class 'str'>
'Hello, Geeks!' <class 'str'>
[1, 2, 3] <class 'str'>
{1, 2, 3} <class 'str'>
Explanation:repr(object) function returns a string representation of all the data-types, preserving their structure, and type(repr(l)) confirms that the output is of type str.
__repr__ method in custom classes defines how an object is represented as a string. It helps in debugging by showing useful details about the object. Here's an example:
Person('Geek', 9)
Explanation:
In the previous example, we can recreate the Person object from the converted str object by repr() funtion using eval() function, here's how:
Person('Alice', 25)
Person('Alice', 25)
Person('Alice', 25)
Alice 25
Explanation:
To know the difference between str and repr Click here.