Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return or print in __str__ method in python

Tags:

python

In the multiple choice question I'm stucked in, there are three options. Here goes the question:

Which of the following is a definition of the _str_method?

1. def __str__(self):
      print "(%s, %s, %s)" % (self._n, self._p, self._b)

2. def __str__(self):
      return "(%s, %s, %s)" % (self._n, self._p, self._b)

3. Both

I tested both of them, and both worked, but it is said that (2) is the answer.

The answers of all other similar questions also say that the function with 'print' is not the right one.

Is the answer wrong?

Thanks

like image 253
Kev M Avatar asked Oct 31 '25 20:10

Kev M


2 Answers

From the official documentation (emphasis mine):

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

As the first version does not return a string object, it must be wrong.

like image 171
moooeeeep Avatar answered Nov 02 '25 11:11

moooeeeep


Only the second method actually returns anything. This means that if you use str explicitly, for example like this:

>>> a = str(myobj)

then only the second method allows you to store the result in a. With the first method, the string would be printed (which already would be wrong), and a would be set to None.

You would even notice this if you just used

>>> print(myobj)

although that's easier to miss: If the __str__() method was defined according to your first example, calling print() on your object would execute that method, printing the string, then returning None to the print function which would then print an empty line. So you'd get an extra, unwanted linefeed.

like image 32
Tim Pietzcker Avatar answered Nov 02 '25 11:11

Tim Pietzcker