Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


The Python repr() function returns the printable representable 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 below example, 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 below example, 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

5