Inheriting automatic attributes initializer considered harmful?

Alex Martelli aleax at mac.com
Wed Oct 17 11:13:31 EDT 2007


Andrew Durdin <adurdin at gmail.com> wrote:

> On 10/17/07, Thomas Wittek <mail at gedankenkonstrukt.de> wrote:
> >
> > Writing such constructors for all classes is very tedious.
> > So I subclass them from this base class to avoid writing these constructors:
> >
> >   class AutoInitAttributes(object):
> >       def __init__(self, **kwargs):
> >           for k, v in kwargs.items():
> >               getattr(self, k) # assure that the attribute exits
> >               setattr(self, k, v)
> >
> > Is there already a standard lib class doing (something like) this?
> > Or is it even harmful to do this?
> 
> It depends on your kwargs and where they're coming from.  You could do
> something like this, for example:
> 
>     def fake_str(self):
>         return "not a User"
> 
>     u = User(__str__=fake_str)
>     str(u)

...and, if you did, that would be totally harmless (in a new-style class
as shown by the OP):

>>> class AutoInitAttributes(object):
...       def __init__(self, **kwargs):
...           for k, v in kwargs.items():
...               getattr(self, k) # assure that the attribute exits
...               setattr(self, k, v)
... 
>>> class User(AutoInitAttributes): pass
... 
>>> def fake_str(self):
...         return "not a User"
... 
>>> u = User(__str__=fake_str)
>>> str(u)
'<__main__.User object at 0x635f0>'
>>> 

fake_str is not called, because special-method lookup occurs on the
TYPE, *NOT* on the instance.

The OP's idea is handy for some "generic containers" (I published it as
the "Bunch" class back in 2001 in
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308>, and I
doubt it was original even then); it's not particularly recommended for
classes that need to have some specific *NON*-special methods, because
then the "overwriting" issue MIGHT possibly be a (minor) annoyance.


Alex



More information about the Python-list mailing list