Python __repr__() magic method
Last Updated :
05 May, 2023
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")
# 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
Similar Reads
Python - __lt__ magic method
Python __lt__ magic method is one magic method that is used to define or implement the functionality of the less than operator "<" , it returns a boolean value according to the condition i.e. it returns true if a<b where a and b are the objects of the class. Python __lt__ magic method Syntax S
2 min read
Python __add__() magic method
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
1 min read
Python __len__() magic method
Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or eq
2 min read
Python reversed() Method
reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example:Pythona = ["nano", "swift", "bolero", "BMW"]
3 min read
Python | Decimal sqrt() method
Decimal#sqrt() : sqrt() is a Decimal class method which returns the Square root of a non-negative number to context precision. Syntax: Decimal.sqrt() Parameter: Decimal values Return: the Square root of a non-negative number to context precision. Code #1 : Example for sqrt() method Python3 # Python
2 min read
Python iter() method
Python iter() method is a built-in method that allows to create an iterator from an iterable. An iterator is an object that enables us to traverse through a collection of items one element at a time. Letâs start by understanding how iter() works with a simple example.Pythona = [10, 20, 30, 40] # Con
2 min read
Python hash() method
Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary.Python hash() function SyntaxSyntax : hash(obj)Parameters : obj : The object which we need t
6 min read
Python setattr() method
Python setattr() method is used to assign the object attribute its value. The setattr() can also be used to initialize a new object attribute. Also, setattr() can be used to assign None to any object attribute. Example : Python3 class Person: def __init__(self): pass p = Person() setattr(p, 'name',
3 min read
Python List methods
Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, weâll explore all Python list methods with a simple example.List MethodsLet's look at different list methods in Python:append(): Adds an
3 min read
Python | Decimal scaleb() method
Decimal#scaleb() : scaleb() is a Decimal class method which returns the first operand after adding the second value its exp. Syntax: Decimal.scaleb() Parameter: Decimal values Return: the first operand after adding the second value its exp. Code #1 : Example for scaleb() method Python3 # Python Prog
2 min read