[Tutor] How to write the __str__ function
Alan Gauld
alan.gauld at yahoo.co.uk
Sun May 14 20:27:22 EDT 2017
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.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list