[Tutor] Beginners question

Alan Gauld alan.gauld at yahoo.co.uk
Sun Apr 5 13:41:39 EDT 2020


On 05/04/2020 04:05, DL Neil via Tutor wrote:

> Contrarily, when working with classes/objects I rapidly grew sick of 
> writing self. or instanceNM. in front of every attribute to be printed!

You can of course override the __str__ method so you only need to say

print(myobject)

or

print (" My object is ", myobject)

But it is less flexible since you must decide in advance which
fields and in which order/format they appear.

But it is definitely more OO than accessing the  fields directly
just to print it! Which makes me wonder....

Does anyone know if thee are hooks into the formatting data that
can be applied when writing a __str__ method? For example with floats
you can specify width and precision options in the format string. It
would be cool if there was a way to access those from within
__str__() so that you could honor them (for example use them
in fomatting numeric values before outputting the string
representation.) But I suspect those specifiers are only visible
in the string format method.

As it is all you can do is specify string formatting, which
boils down to length, padding and justification.

-- 
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