Kev M
Kev M

Reputation: 73

return or print in __str__ method in 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

Upvotes: 4

Views: 4313

Answers (3)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

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.

Upvotes: 6

nos
nos

Reputation: 229108

Here's what python say

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.

Only choice 2 returns a string.

And it would also make sense, __str__ is supposed to give you a string representation of the object. If you want to get the string representation of an object , and sometimes place it in a database, other times write to a file, it doesn't make sense that you have a __str__ method that prints it to the screen/stdout.

Upvotes: 0

moooeeeep
moooeeeep

Reputation: 32522

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.

Upvotes: 9

Related Questions