Python __repr__() magic method
Python __repr__() is one of the magic methods 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 needs.
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
In this example, we define a GFG class with three instance variables f_name, m_name, and l_name representing the first, middle, and last name of a person, respectively. The __repr__() method is defined to return a string representation of the instance in a format that can be used to recreate the object.
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))
|
Output:
GFG("Geeks","For","Geeks")
Difference between __str__() and __repr__() magic method
In this example, we define a GFG class with one instance variable name representing the name of a person. The __str__() method is defined to return a human-readable string representation of the instance, while the __repr__() method is defined to return a string representation of the instance that can be used to recreate the object.
When we create an instance of the GFG class and call __str__() or __repr__() directly on the object, the respective method is called and returns a string that represents the object.
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__())
|
Output:
Name is GeeksForGeeks
GFG(name=GeeksForGeeks)
You can also read str() vs repr() in Python.
__str__() and __repr__() Examples Using a Built-In Class
In this example, we define a subclass of tuple called MyTuple that overrides the __str__() and __repr__() methods. When we call Python str() or Python repr() on an instance of MyTuple, the custom __str__() and __repr__() methods are called, respectively.
Python3
class MyTuple( tuple ):
def __str__( self ):
return f "MyTuple({super().__str__()})"
def __repr__( self ):
return f "MyTuple({super().__repr__()})"
mt = MyTuple(( 1 , 2 , 3 ))
print (mt.__repr__())
print (mt.__str__())
|
Output:
MyTuple((1, 2, 3))
MyTuple(MyTuple((1, 2, 3)))
__str__() and __repr__() Examples Using a New Class
In this example, we define a Book class with three instance variables title, author, and pages representing the title, author, and number of pages of a book, respectively. The __str__() method is defined to return a string representation of the instance in a human-readable format, while the __repr__() method is defined to return a string representation of the instance that can be used to recreate the object.
When we create an instance of the Book class and call str() on it, the __str__() method is called and returns a human-readable string that represents the object. When we call repr() on it, the __repr__() method is called and returns a string that represents the object in a way that it can be recreated.
Python3
class Book:
def __init__( self , title, author, pages):
self .title = title
self .author = author
self .pages = pages
def __str__( self ):
return f "{self.title} by {self.author}, {self.pages} pages"
def __repr__( self ):
return f "Book('{self.title}', '{self.author}', {self.pages})"
book1 = Book( "The Hitchhiker's Guide to the Galaxy" , "Douglas Adams" , 224 )
print ( "Using str(): " , str (book1))
print ( "Using repr(): " , repr (book1))
|
Output:
Using str(): The Hitchhiker's Guide to the Galaxy by Douglas Adams, 224 pages
Using repr(): Book('The Hitchhiker's Guide to the Galaxy', 'Douglas Adams', 224)
Practical usage of __repr__() magic method
This code creates a Color class with an __init__() method that takes a suffix parameter and sets an instance variable self. suffix to that value. It also sets another instance variable self. title to a string that includes the suffix. Finally, it defines an __repr__() method that returns a string representation of the object.
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" )
c2 = eval ( repr (c1))
print ( "c1.title:" , c1.title)
print ( "c2.title:" , c2.title)
|
Output:
c1.title: Golden Yellow
c2.title: Golden Yellow
Last Updated :
05 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...