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

John Roth johnroth at ameritech.net
Sun Sep 23 23:15:01 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?

The thing is, that's exactly what a factory function is for - it does
whatever
special case logic is required to get the right class instantiated, so that
the code doesn't have to be replicated elsewhere in the system.

John Roth





More information about the Python-list mailing list