![]() |
VOOZH | about |
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.
Syntax: object.__repr__()
- object: The object whose printable representation is to be returned.
Return: Simple string representation of the passed object.
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.
Output:
GFG("Geeks","For","Geeks")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.
Output:
Name is GeeksForGeeks GFG(name=GeeksForGeeks)
You can also read str() vs repr() in Python.
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.
Output:
MyTuple((1, 2, 3)) MyTuple(MyTuple((1, 2, 3)))
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.
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)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.
Output:
c1.title: Golden Yellow c2.title: Golden Yellow