possible attribute-oriented class

Scott David Daniels Scott.Daniels at Acm.Org
Fri Sep 4 17:35:11 CEST 2009


Ken Newton wrote: ...
> I would appreciate comments on this code. First, is something like
> this already done? Second, are there reasons for not doing this?  ...
> 
> class AttrClass(object):
       ...
>     def __repr__(self):
>         return "%s(%s)" % (self.__class__.__name__, self.__dict__.__repr__())
>     def __str__(self):
>         ll = ['{']
>         for k,v in self.__dict__.iteritems():
>             ll.append("%s : %s" % (k, str(v)))
>         return '\n'.join(ll) + '}'

Yes, I've done stuff something like this (I use setattr /
getattr rather than direct access to the __dict__).

You'd do better to sort the keys before outputting them, so
that you don't confuse the user by printing two similarly
built parts in different orders.

Personally, I'd filter the outputs to avoid names beginning
with '_', as they may contribute to clutter without adding
much information.

An equality operator would be nice as well (don't bother with
ordering though, you get lost in a twisty maze of definitions
all different).

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list