[Tutor] Beginners question

Peter Otten __peter__ at web.de
Sun Apr 5 15:36:22 EDT 2020


Alan Gauld via Tutor wrote:

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

You can write a custom __format__() method: 

$ cat tmp.py
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=}"
        elif spec == "long":
            return f"{first} {last}"
        elif spec == "short":
            return f"{first[:1]}{last[:1]}"
        elif spec == "":
            return str(self)
        raise ValueError(f"format_spec {spec!r} not supported")

    def __str__(self):
        return "S:" + format(self, "long")

    def __repr__(self):
        return "R:" + format(self, "debug")


p = Person("Alan", "Gauld")

print(f"default: {p}")
print(f"debug: {p:debug}")
print(f"explicit !s: {p!s}")
print(f"explicit !r: {p!r}")
print(f"long: {p:long}")
print(f"short: {p:short}")
$ python3.8 tmp.py
default: S:Alan Gauld
debug: first='Alan', last='Gauld'
explicit !s: S:Alan Gauld
explicit !r: R:first='Alan', last='Gauld'
long: Alan Gauld
short: AG
$



More information about the Tutor mailing list