[Tutor] How to write the __str__ function

Sydney Shall s.shall at virginmedia.com
Mon May 15 11:43:33 EDT 2017


On 15/05/2017 01:27, Alan Gauld via Tutor wrote:
> On 14/05/17 19:03, Sydney Shall wrote:
>
>> 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),
>
> Here endeth the first string
>
>>                 "\n The fractional sigma (FractionalSTD)"
>>                 " of UCC that was input was %7.5f " % (self.fractsigma_ucc))
>
> And here the second. Returning two strings separated
> by a comma makes it a tuple. Instead put the two values in a tuple at
> the end of a single concatenated string.
>
> And while at it make life easier for your self and use triple quotes:
>
> def __str__(self):
>     return """
>                Output from __str__ of POCWP.
>
> After the first turnover, during the
> 'Population Of Capitals Init' cycle,
> the productivities were raised from 1.0
> to a specific Unit Constant Capital (UCC)
> for each specific capital:
>  The input value for the mean of UCC was %7.5f
>  The fractional sigma (FractionalSTD) of UCC that was input was %7.5f
> """ % ( self.ucc, self.fractsigma_ucc)
>
> Tweak the formatting to suit.
>
> However, I'm not sure thats really a good use of __str__,
> I might be tempted to make that an explicit method that's
> called pprint()  - for pretty-print - or somesuch.
> __str__() methods are usually a fairly cocise depiction
> of the objects state that you can embed in a bigger string.
>
> Maybe pprint() would look like
>
> def pprint(self):
>     return """
>                Output from __str__ of POCWP.
>
> After the first turnover, during the
> 'Population Of Capitals Init' cycle,
> the productivities were raised from 1.0
> to a specific Unit Constant Capital (UCC)
> for each specific capital: %s""" % self
>
> And __str__()
>
> def __str__(self):
>    return """
> The input value for the mean of UCC was %7.5f
> The fractional sigma (FractionalSTD) of UCC that was input was %7.5f """
> % (self.ucc, self.fractsigma_ucc)
>
> Thus pprint() uses str() to create the long version while str()
> just gives the bare bones result.
>
> Just a thought.
>
Here endeth the second (! -presumptious?) string.

"""I would like to thank you all for the five lessons.

The advice of course gave me several useful ways of outputting data.

I believe I now have a better understanding of output."""

Many thanks.


-- 
Sydney


More information about the Tutor mailing list