Dealing with the __str__ method in classes with lots of attributes

Andreas Tawn andreas.tawn at ubisoft.com
Thu May 10 09:33:03 EDT 2012


Say I've got a class...

class test(object):
    def __init__(self):
        self.foo = 1
        self.bar = 2
        self.baz = 3

I can say...

def __str__(self):
   return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo, self.bar, self.baz)

and everything's simple and clean and I can vary the formatting if I need to.

This gets ugly when the class has a lot of attributes because the string construction gets very long.

I can do...

return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo,
                                                                    self.bar,
                                                                    self.baz)

which is an improvement, but there's still a very long line.

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?

Cheers,

Drea

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



More information about the Python-list mailing list