What’s the difference between “__str__” and “__repr__” in python

Photo by Surface on Unsplash

The goal of __repr__is to be unambiguous and __str__ is to be readable. By the end of this article, you may be able to understand how it differs.

According to official python documentation,__repr__ a built-in function is used to compute an object's “official” string reputation, while __str__ is a built-in function that computes the “informal” string representations of an object.

Let’s try to create a Student class that accepts two parameters as input. After initializing the class, if you inspect the object, all you get is a string containing the class name and the id of the object instance.

Let's try to add a dunder method __str__ with string to return. When we try to print the class, we will get the string returned from the method. But when you inspect the class, it will return the address of the object.

Now we will try to add __repr__ the method with string to return. When we print or inspect the class, we will get the string returned from the repr method.

If we include both __repr__ and __str__ inside the class, when we use the print statement __str__ will be called and for other __repr__ will be returned

Conclusion

In short, when we use a print statement, it checks for the __str__ method. If it is not available, then it checks for the __repr__ method.

Both __str__() and __repr__( ) are used to compute a string representation for objects under

__repr__ is for developers (purpose of debugging and development).

__str__ It is for customers(creating human-readable output).

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

KnowledgeBase/Windows — Squid Web Proxy Wiki

Create a list of all subscriptions and who receives them on Tableau Server

Laravel Dusk: Tinker

CS371p Spring 2022: David Klingler

Understanding different Run-Times of Quick Sort

ZKPAD — Complete tasks, earn and exchange XP, get $ZKP tokens!

Highlights AWS re:Invent 2019

Ubuntu desktop on Raspberry Pi 4

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sachinjose

Sachinjose

More from Medium

How to be Basic in Python

Number of Good Pairs — Day 101(Python)

Is Both Or Not|Codechef Solution in Python

A Python Between the Sheets