generic class for everything?

Alex Martelli aleax at
Fri Mar 28 11:58:50 CET 2003

Rob Brown-Bayliss wrote:
> I had though of a class that has:
> unique identifier
> name
> description
> stuff
> where stuff is basically a large text field so item might be:
> 1234
> "No Gas"
> "The fule tank has run dry"
> "fule(0) fule_light(on) power_out(-100%) electrical_out(-100%) lights(0)
> "
> and then parse  the stuff field modifying the parent class.
> The only other option I can think of is having the class have avariable
> for every single thing that can happen, but that seems to be a night
> mare
> Any thoughts?

Python's dynamism can serve you well here -- different instances can
easily have different subsets of the attributes, and a "template
method" can easily introspect "self" to find out.  For example (a
small enhancement is possible to this in 2.3, using sets, but I'll
code to 2.2 levels as it's not much of a difference anyway):

import warnings

class Happenstances:

    parent_components = ("fuel fuel_light power_out brakes engine"
        "electrical_out lights theft_alarm tires spare_tire").split()
    parent_components = dict(zip(parent_components,parent_components))

    def __init__(self, name, description, parent=None, **stuff):
        self.uid = getuid() = name
        self.description = description
        self.parent = parent
        for comp, value in stuff.iteritems():
            if comp in parent_components:
                setattr(self, comp, value)
                msg = "Unk component %s ignored in %s" % (comp, name)

    def makeitso(self, parent=None):
        parent = parent or self.parent
        if parent is None:
            msg = "Happenstance %s can't happen to None" %
        for comp in parent_components:
            value = getattr(self, comp, None)
            if value is None: continue
            setattr(parent, comp. value)


More information about the Python-list mailing list