Skip to content
Related Articles
Open in App
Not now

Related Articles

Python __repr__() magic method

Improve Article
Save Article
  • Last Updated : 04 Sep, 2022
Improve Article
Save Article

Python __repr__() is one of the magic method that returns a printable representation of an object in Python that can be customized or predefined, i.e. we can also create the string representation of the object according to our need.

Python __repr__() magic method Syntax:

Syntax: object.__repr__()

  • object: The object whose printable representation is to be returned.

Return: Simple string representation of the passed object.

Python __repr__() method Example:

Python3




class GFG:
    
    def __init__(self, f_name, m_name, l_name):
        self.f_name = f_name
        self.m_name = m_name
        self.l_name = l_name
  
    def __repr__(self):
        return f'GFG("{self.f_name}","{self.m_name}","{self.l_name}")'
  
gfg = GFG("Geeks", "For", "Geeks")
print(repr(gfg))


GFG("Geeks","For","Geeks")

Explanation:

Whenever an object is passed to the repr() method then internally the __repr__() method of that particular object is called and the string representation of the object is generated, therefore we can say that repr() basically gives the representation of the object.

Example 1: Difference between __str__() and __repr__() magic method

Python3




class GFG:
  
    def __init__(self, name):
        self.name = name
  
    def __str__(self):
        return f'Name is {self.name}'
  
    def __repr__(self):
        return f'GFG(name={self.name})'
  
  
obj = GFG('GeeksForGeeks')
  
print(obj.__str__())
print(obj.__repr__())


Name is GeeksForGeeks
GFG(name=GeeksForGeeks)

Example 2: Practical usage of __repr__() magic method

In this example, we have created one object of the Color class (c1) with one suffix value. Then, we have used eval() function on the return value of __repr__() to reconstruct the same object (c1) with same suffix value.

Python3




class Color:
    def __init__(self, suffix):
        self.suffix = suffix
        self.title = f"Golden {suffix}"
  
    def __repr__(self):
        return f"Color('{self.suffix}')"
  
  
c1 = Color("Yellow")
# create another object with same params as c1
# using eval() on repr()
c2 = eval(repr(c1))
  
print("c1.title:", c1.title)
print("c2.title:", c2.title)


Output:

c1.title: Golden Yellow
c2.title: Golden Yellow

Conclusion:

  •  __repr__() magic method returns a printable representation of the object.
  • The __str__() magic method returns the string representation which is more user-friendly i.e. easy to understand, whereas __repr__() representation contains information about the object so that it can be reconstructed.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!