This repr()
function returns a string containing a printable representation of an object.
repr(*object*)
Here,
Note: For many types, repr()
function makes an attempt to return a string that would yield an object with the same value when passed to eval()
, otherwise the representation is a string enclosed in angle brackets.
>>> repr(1)
'1'
>>> repr([1, 2])
'[1, 2]'
>>> repr({'a': 1, 'b': 2})
"{'a': 1, 'b': 2}"
>>> repr('hello')
"'hello'"
>>> repr("hello")
"'hello'"
>>> repr("""hello""")
"'hello'"
>>> repr('hello')
"'hello'"
>>> eval(repr('hello'))
'hello'
Here, repr(’hello’)
returned “’hello’”, inside double quotes while passing repr()
to *eval()*
returned just ‘hello’.
>>> class class1:
... pass
...
>>> repr(class1())
'<__main__.class1 object at 0x7efe541b9120>'
__repr__()
(override/implement)>>> class class2:
... def __repr__(self):
... return 'class2 output'
...
>>> repr(class2())
'class2 output'