/  Technology   /  What is the difference between __str__ and __repr__ in Python?
difference between __str__ and __repr__ in Python

What is the difference between __str__ and __repr__ in Python?

 

In Python, the object class has a number of magic methods(methods that start and end with double underscores). We never call these methods directly. A corresponding built-in function calls one of these magic methods internally. Let’s stick to str and repr in this article. So the built-in str() function invokes the  __str__() magic method and the built-in repr() function invokes the __repr__() magic method. 

Both these functions give the string representation of a string.

Example:

a= 100
print(str(a))
print(a.__str__())

a= 100
print(repr(a))
print(a.__repr__())

Output:

 

Now let’s see what’s the use of two different functions for the same functionality. Look at the example below.

Example:

a= 'Python with i2tutorials'
print (str(a))

a= 'Python with i2tutorials'
print (repr(a))

Output:

   

We have passed a string ‘Python with i2tutorials’ to a variable a. We can see that both these functions, when called, are returning the corresponding string but the repr() function adds quotes to it. This is the formal representation of a string whereas str() gives the informal representation of a string.

 

The formal representation adds a lot of value to the information and a lot of detail which is much helpful for developers while debugging.

 

The informal representation aims at increasing the readability of the output for the users. We can understand this by the following example.

Example:

import datetime
today = datetime.datetime.now()
repr(today)

import datetime
today = datetime.datetime.now()
str(today)

Output:

 

Let’s make these functions work for our own defined class, class A and an object a.

Example:

class A:

   def__init__(self, state_name, state_capital):
      self.state = state_name
      self.capital = state_capital

   def__str__(self):
      return f'State name is {self.state} and capital is {self.capital}'

   def__repr__(self)
      returnf'State(name={self.state}, capital={self.capital})'

a= A('Telangana', 'Hyderabad')

print(a.__str__())
print(a.__repr__())

Output:

Note: We must never use these functions directly, we should always use the str() and repr() functions, which will call the underlying __str__() and __repr__() functions.

 

Leave a comment