Is there a way to instantiate a subclass from a class constructor?

Chris Tavares christophertavares at earthlink.net
Sun Sep 23 16:40:52 EDT 2001


"Paul Rubin" <phr-n2001 at nightsong.com> wrote in message
news:7xofo2l2kk.fsf at ruckus.brouhaha.com...
> "Terry Reedy" <tjreedy at home.com> writes:
> > "> The obvious workaround is to define a function that calls the
> > appropriate
> > > constructor, e.g.
> > >   def newpoly(sides):
> > >     if sides==3: return Triangle(...)
> > >     ...
> >
> > A factory function like this is a standard solution that has been
> > discussed in several posts on this list.  Don't knock it.
>
> I'm not knocking it, I just don't see how to extend the class from
> additional base classes without having to add more special code to
> the factory function, which is against the OO spirit.  Any thoughts?
>

I've got a possibly sick solution. Assuming that the only parameter you're
dealing with is the sides, then you can use a dictionary and the fact that
classes are callable objects, something like this:

class GenericPolygon:
    pass

class Triangle:
    pass

class Rectangle:
    pass

def newPolygon( sides ):
    lookup = { 3 : Triangle, 4 : Rectangle }
    creator = lookup.get( sides, GenericPolygon )
    return creator()

Then to update your class list all you need to do is add new entries to
lookup. If you've got more complex criteria (more than one parameter, for
example) you can either a) if the criteria are simple constants you can use
tuples as the dict keys rather than numbers or b) replace lookup with a list
of predicate functions that test if the parameters match criteria for each
class.

-Chris






More information about the Python-list mailing list