Dealing with the __str__ method in classes with lots of attributes
Chris Angelico
rosuav at gmail.com
Thu May 10 10:33:13 EDT 2012
On Thu, May 10, 2012 at 11:33 PM, Andreas Tawn <andreas.tawn at ubisoft.com> wrote:
> 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)
This might be of use:
return """foo: {foo}
bar: {bar}
baz: {baz}""".format(**self.__dict__)
You're repeating yourself a bit, but this allows the labels to differ
from the format tags. If you're certain that you don't need that
flexibility, you could generate the format string dynamically:
return "\n".join(x+": {"+x+"}" for x in
("foo","bar","baz")).format(**self.__dict__)
That scales more nicely as the number of elements desired increases
(while still being 100% explicit - the presence and order of elements
is governed by the tuple), but is a bit inflexible and complicated.
I'd be inclined toward the triple-quoted-string one.
Tim Toady.
ChrisA
More information about the Python-list
mailing list