Simple base object for "struct like" classes

Chris Green cmg at uab.edu
Tue Sep 25 22:49:04 EDT 2001


I'm currently going through an SQL db that we have and setting up base
classes for working with it.  I ended up doing a lot of cut and paste
code and ended up coming up with a class that takes a list of keywords
arguments to set class attributes.

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.

The only real advantage this seems to have over a UserDict is the
obj.blah syntax though it seems upon reading the documentation after I
had the inspiration that __getattr__ and __setattr__ could be used to
achieve the same thing. 

Each subclass gets an attribute_dict that has a list of keys and
default values.

I check to make sure attributes aren't already set as they could be in
a subclass and I provide a validate method for initialization
bookkeping.

This simple lets me do things like

class thingie(Simple):
    attribute_dict = {"thingie1": ['a','b','c'],
                      "thingie2": "weee"
                      }

Simple class follows:

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):
        """ Creates an instance of a Simple Object

        see  Simple.__doc__        
        """

        # if there is a keyword in our attribute list AND
        # we don't already have that method defined, set that local member
        # other wise, just set it to None

        # it would be set to something in a subclass perhaps.

        attribute_dict = self.attribute_dict
        
        for key in attribute_dict.keys():
            if kws.has_key(key) and not self.__dict__.has_key(key):
                self.__dict__[key] = kws[key]
            elif not self.__dict__.has_key(key):
                self.__dict__[key] = attribute_dict[key]

        # if we don't support said attribute
        # 'scuse me while kiss the sky
        for key in kws.keys():
            try:
                nothing = attribute_dict[key]
            except KeyError:
                raise AttributeError, "No such member: " + str(key)

        # make sure that all of types are ok
        self.validate()

    def validate(self):
        """ override this method to introduct some error checking into
        the constructor function

        This method will be called after all attributes are set so that
        all data is set to valid types
        """
        pass

-- 
Chris Green <cmg at uab.edu>
Fame may be fleeting but obscurity is forever.



More information about the Python-list mailing list