Simple base object for "struct like" classes

Martin von Loewis loewis at informatik.hu-berlin.de
Wed Sep 26 13:02:36 EDT 2001


Chris Green <cmg at uab.edu> writes:

> I've just started playing with this type of dynamic coding so I was
> going to see what else people have done and I hope that this code is
> useful to someone else.  __dict__ does say it is read only in:
> http://www.python.org/doc/current/lib/specialattrs.html
> so perhaps I'm being dangerous.

That only means that you cannot assign to __dict__. I.e. 

  self.__dict__ = kw

is not good. Instead,

  self.__dict__.update(kw)

doesn't replace the dictionary, but only changes its contents.

> Simple class follows:

It appears that you can make this class even simpler:

> class Simple:
>     """ To use this class, simply define a subclass of this object
>     and in that subclass, override the attribute_dict value.
> 
>     The constructor accepts a keyword hash of objects and will map the
>     hash values into keys
>     """
> 
>     # by default, support no attributes
>     attribute_dict = {}
> 
>     def __init__(self, **kws):
          dict = self.__dict__
          dict.update(self.attribute_dict)
          for key, value in kws.items():
              if dict.has_key(key):
                   dict[key] = value
              else:
                   raise AttributeError,"No member %s in %s" % \
                       (key, self.__class__.__name__)

HTH,
Martin



More information about the Python-list mailing list