[Tutor] Beginners question
Alan Gauld
alan.gauld at yahoo.co.uk
Sun Apr 5 18:50:07 EDT 2020
On 05/04/2020 20:36, Peter Otten wrote:
> Alan Gauld via Tutor wrote:
>> Does anyone know if thee are hooks into the formatting data that
>> can be applied when writing a __str__ method?
> You can write a custom __format__() method:
Cool. I completely missed that.
Time to start reading the docs and having a play.
Looking at the code below, does this only work with
format strings? Or was it only introduced with
format strings? I'm still on 3.6 so that may be why
I've never seen it before...
> class Person:
> def __init__(self, first, last):
> self.first = first
> self.last = last
>
> def __format__(self, spec):
> first = self.first
> last = self.last
>
> if spec == "debug":
> return f"{first=}, {last=}"
> print(f"debug: {p:debug}")
> debug: first='Alan', last='Gauld'
--
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