Python repr() Function
Python repr() Function returns a printable representation of the object passed to it.
Syntax:
repr(object)
Parameters:
object : The object whose printable representation is to be returned.
Return Value:
Returns a string.
A __repr__() method can be defined in a class to control what this function returns for its objects.
Example 1: passing string object to repr method
Python3
strObj = 'geeksforgeeks' print ( repr (strObj)) |
Output
'geeksforgeeks'
Example 2: passing set object to repr method
Python3
num = { 1 , 2 , 3 , 4 , 5 } # printable representation of the set printable_num = repr (num) print (printable_num) |
Output
{1, 2, 3, 4, 5}
Example 3: Defining __repr__() method in class
Python3
class geek: def __init__( self , name): self .name = name # defining __repr__() method to control what # to return for objects of geek def __repr__( self ): return self .name geek1 = geek( 'mohan' ) print ( repr (geek1)) |
Output
mohan
Explanation:
The repr() is defined in the class and the special method returns the name attribute of the object, The object of geek class is created and the string is passed to it, and the printable representation of the string is print.