Dealing with the __str__ method in classes with lots of attributes

Karl Knechtel zahlman at gmail.com
Sat May 12 08:36:02 EDT 2012


On Thu, May 10, 2012 at 9:33 AM, Andreas Tawn <andreas.tawn at ubisoft.com> wrote:
> And there's also something like...
>
> return "\n".join((": ".join((str(k), str(self.__dict__[k]))) for k in self.__dict__))
>
> which is a nice length, but I lose control of the order of the attributes and the formatting is fixed. It also looks a bit too much like Lisp ;o)
>
> Is there a better way?

If you don't care about being able to change the attributes
dynamically, define the `__slots__` of your class, and then you can
use

return '\n'.join('%s: %s' % (name, getattr(self, name)) for name in
self.__slots__)

Calling `getattr` is probably more Pythonic than looking things up in
`__dict__`, string formatting can take care of "casting" (converting,
really) for you, and the nested `join` is really overkill :) Anyway
the main point is that `__slots__` is a list, and thus has a defined
order.

>
> p.s. I may want to substitute __repr__ for __str__ perhaps?

Depending. Sometimes you want them to behave the same way. Since
functions are objects, this is as simple as `__repr__ = __str__`. :)

p.s. Is Python seeing a lot of use at Ubisoft or is this just for
personal interest (or perhaps both)?

-- 
~Zahlman {:>



More information about the Python-list mailing list