Simple base object for "struct like" classes

Martin von Loewis loewis at
Wed Sep 26 19:02:36 CEST 2001

Chris Green <cmg at> 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:
> so perhaps I'm being dangerous.

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

  self.__dict__ = kw

is not good. Instead,


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__
          for key, value in kws.items():
              if dict.has_key(key):
                   dict[key] = value
                   raise AttributeError,"No member %s in %s" % \
                       (key, self.__class__.__name__)


More information about the Python-list mailing list