[Tutor] How to write the __str__ function

Sibylle Koczian nulla.epistola at web.de
Sun May 14 15:44:27 EDT 2017


Am 14.05.2017 um 20:59 schrieb Martin A. Brown:
>
> Hello and greetings,
>
>> I need some advice that I have been embarrased to ask for, because
>> I think that my error is so elementary.
>
> Well, there are two benefits to trying to write down questions like
> this when you encounter them.
>
>   1) Rubber Duck debugging (if you have not heard of it); sometimes
>      the act of describing the problem / question is enough for you
>      to figure it out in the process
>
>   2) If you don't quite get there, then you have a description that
>      somebody can easily review and respond to.
>
>> I have written, as advised by the tutors, a complex program in a
>> topic that interests me. The program works well and the tests are
>> OK.
>
> Right on!
>
>> Now I want to add a __str__ function, which I thought would be
>> straightforward. But I cannot get it right.
>>
>> The code that I have so far is as folows:
>>
>> def __str__(self):
>>        return("\n"
>>               "               Output from __str__ of POCWP. "
>>               "\n"
>>               "\n After the first turnover, during the "
>>               "'Population Of Capitals Init' cycle,"
>>               "\n the productivities were raised from 1.0 "
>>               "\n to a specific Unit Constant Capital (UCC) "
>>               "for each specific capital: "
>>               "\n The input value for the mean of UCC "
>>               "was %7.5f" % (self.ucc),
>>               "\n The fractional sigma (FractionalSTD)"
>>               " of UCC that was input was %7.5f " % (self.fractsigma_ucc))
>>
>> The error message is:
>>
>> TypeError: __str__ returned non-string (type tuple)
>>
...
> I have, therefore, a few small suggestions:
>
>   1. Put all of the variables replacements at the end.
>
>         thing = ("var x=%s\nvar y=%s" % (x,y))
>
>   2. When creating the replacements, also use tuples (see next
>      point, too):
>
>         "was %7.5f" % (self.ucc,)
>

If you put this into your original string, it won't work. Try this very 
simple example:

st = "abc %d" % 7 "def"   # <- SyntaxError

The replacements definitely belong at the end, all together.

But an additional question: do you really want to get this very long 
text every time you need an instance of your class as a string? Even if 
it's put into another sentence using string formatting? Like this for 
example (assuming your class is called MyClass):

x = MyClass(some, args)
s = """This is an instance of MyClass with the value %s. It was 
initialized with the values some = %s, args = %s.""" % (x, some, args)
print(s)

Greetings,
Sibylle




More information about the Tutor mailing list