Python Tutorial Python Advanced Python References Python Libraries

Python repr() Function



The Python repr() function returns the printable representation of a given object.

Syntax

repr(obj)

Parameters

obj Required. Specify the object whose printable representation is to be returned.

Example: using repr() function

In the example below, repr() function returns the printable representation of variable var.

var = 'Hello'
print(repr(var))

The output of the above code will be:

'Hello'

Example: using __repr__() function with class

__repr()__ function can be defined inside a class which overrides the internal repr() function. In the example below, the class object uses internal repr() function to get the printable representation of it.

class person:
  def __init__(self, name):
    self.name = name

p = person('John')
print(repr(p))

The output of the above code will be:

<__main__.person object at 0x7f6904bd3d00>

But, when __repr()__ function is defined inside a class, it overrides the internal repr() function. This feature can be used to get the customized printable representation of a class object. Consider the following example.

class person:
  def __init__(self, name):
    self.name = name

  def __repr__(self):
    return repr('name:' + self.name)

p = person('John')
print(repr(p))

In this case, the output will be:

'name:John'

❮ Python Built-in Functions