Dealing with the __str__ method in classes with lots of attributes

Andreas Tawn andreas.tawn at ubisoft.com
Fri May 11 07:16:48 EDT 2012


> This issue bit me once too often a few months ago, and now I have a class called
> "O" from which I often subclass instead of from "object".
> Its main purpose is a friendly __str__ method, though it also has a friendly __init__.
> 
> Code:
> 
>     class O(object):
>       ''' A bare object subclass to allow storing arbitrary attributes.
>           It also has a nicer default str() action, and an aggressive repr().
>       '''
> 
>       def __init__(self, **kw):
>         ''' Initialise this O.
>             Fill in attributes from any keyword arguments if supplied.
>             This call can be omitted in subclasses if desired.
>         '''
>         for k in kw:
>           setattr(self, k, kw[k])
> 
>       def __str__(self):
>         return ( "<%s %s>"
>                  % ( self.__class__.__name__,
>                      ",".join([ "%s=%s" % (attr, getattr(self, attr))
>                                 for attr in sorted(dir(self)) if attr[0].isalpha()
>                               ])
>                    )
>                )

This is a very interesting solution.

I think it might be better suited (for my purpose) to __repr__ rather than __str__, mostly because I still lose control of the order the attributes appear.

I really like the general idea of subclassing object though, because I often have classes with dozens of attributes and __init__ gets very messy.

Chris' dynamically generated format string looks to be my best bet in the absence of a perfect solution.

Cheers,

Drea



More information about the Python-list mailing list