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
From the official documentation (emphasis mine):
object.__str__(self)Called by the
str()built-in function and by the__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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With