The repr()
function is used to get the printable string representation of an object.
Syntax:
repr(object)
The single argument , object
, can be any valid value such as an integer, a string, lists, a user-defined class, a function, etc.
repr(1)
//'1'
repr(list)
//"<class 'list'>"
repr("Python")
//"'Python'"
repr(True)
//'True'
repr({1:'one'})
//"{1: 'one'}"
The built-in print()
function actually prints the string returned by repr(object)
.
User defined objects can customize their printable representation by overriding the __repr__()
method.
class Example1:
def __init__(self):
self.name = 'Instance'
e1 = Example1()
print(e1)
class Example2:
def __init__(self):
self.name = 'Example2 Instance'
def __repr__(self):
return self.name
e2 = Example2()
print(e2)