What is the purpose of __str__ and __repr__?

I really don't understand where the __str__ and __repr__ used in Python are used. I mean, I get __str__ return a string representation of the object. But why do I need this? In what use case? Also, I read about using __repr__

But I don’t understand, where would I use them?

+68
python
Sep 11 '10 at 13:10
source share
6 answers

__repr__

Called by the built-in repr() function and string conversions (backticks) to compute the "official" string representation of an object. If at all possible, it should look like a valid Python expression that can be used to recreate an object with the same value (given the appropriate environment).

__str__

Called by the built-in str() function and the print operator to compute an "informal" string representation of an object.

Use __str__ if you have a class and you need informative / informal output whenever you use this object as part of a string. For example. you can define __str__ for Django models, which are then displayed in the Django admin interface. Instead of something like <Model object> , you get as the person’s first and last name, event name and date, etc.




__repr__ and __str__ similar, in fact they are sometimes equal (an example from the BaseSet class in sets.py from the standard library):

 def __repr__(self): """Return string representation of a set. This looks like 'Set([<list of elements>])'. """ return self._repr() # __str__ is the same as __repr__ __str__ = __repr__ 
+69
Sep 11 '10 at 13:14
source share

The only place you use them is the interactive session. If you print an object, then its call will call its __str__ method, whereas if you just use the object on its own, its __repr__ :

 >>> from decimal import Decimal >>> a = Decimal(1.25) >>> print(a) 1.25 <---- this is from __str__ >>> a Decimal('1.25') <---- this is from __repr__ 

__str__ intended to be as understandable as possible for a person, while __repr__ should be something that could be used to recreate an object, although it often will not be exactly how it was created, as in this case.

It is also not uncommon for both __str__ and __repr__ return the same value (of course, for built-in types).

+47
Sep 11 '10 at 16:48
source share

Grasshopper, if he is in doubt go over the mountain and read Ancient Texts . In them, you will find that __repr __ () should:

If at all possible, it should look like a valid Python expression that can be used to recreate an object with the same value.

+13
Sep 11 '10 at 13:16
source share

Build and previous answers and some more examples. When used correctly, the difference between str and repr is clear. In short, repr should return a string that can be copied to restore the exact state of the object, while str is useful for logging and observing debugging results. Here are some examples to see different results for some well-known libraries.

Datetime

 print repr(datetime.now()) #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411) print str(datetime.now()) #2017-12-12 18:49:27.134452 

str is good for printing to a log file, where as repr can be reassigned if you want to run it directly or upload it as commands to a file.

 x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411) 

Numpy

 print repr(np.array([1,2,3,4,5])) #array([1, 2, 3, 4, 5]) print str(np.array([1,2,3,4,5])) #[1 2 3 4 5] 

in Numpy repr again directly expendable.

Custom Example Vector3

 class Vector3(object): def __init__(self, args): self.x = args[0] self.y = args[1] self.z = args[2] def __str__(self): return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z) def __repr__(self): return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z) 

In this example, repr again returns a string that can be directly used / executed, while str more useful as debug output.

 v = Vector3([1,2,3]) print str(v) #x: 1, y: 2, z: 3 print repr(v) #Vector3([1,2,3]) 

One thing to keep in mind if str not defined, but repr , str will automatically call repr . So it is always good to at least define repr

+7
Dec 13 '17 at 3:06 on
source share

str will be an informal and readable format, while repr will give an official representation of the object.

 class Complex: # Constructor def __init__(self, real, imag): self.real = real self.imag = imag # "official" string representation of an object def __repr__(self): return 'Rational(%s, %s)' % (self.real, self.imag) # "informal" string representation of an object (readable) def __str__(self): return '%s + i%s' % (self.real, self.imag) t = Complex(10, 20) print (t) # this is usual way we print the object print (str(t)) # this is str representation of object print (repr(t)) # this is repr representation of object Answers : Rational(10, 20) # usual representation 10 + i20 # str representation Rational(10, 20) # repr representation 
+1
Jan 10 '18 at 12:57
source share

Let's have a class without the __str__ function.

 class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay emp1 = Employee('Ivan', 'Smith', 90000) print(emp1) 

When we print this instance of the emp1 class, we get the following:

 <__main__.Employee object at 0x7ff6fc0a0e48> 

This is not very useful, and of course, this is not what we want to print if we use it for display (as in html)

So now the same class, but with the __str__ function:

 class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay def __str__(self): return(f"The employee {self.first} {self.last} earns {self.pay}.") # you can edit this and use any attributes of the class emp2 = Employee('John', 'Williams', 90000) print(emp2) 

Now instead of printing what the object is, we get what we specified with the __str__ function returning:

The employee John Williams earns 90000

0
Dec 01 '18 at 0:09
source share



All Articles