[Edu-sig] __init__ returning subclasses

Dustin Mitchell dustin@cs.uchicago.edu
Sun, 21 Oct 2001 21:54:01 -0500 (CDT)


The idiom you're asking about is called 'Virtual Constructors'.  James
Coplien's 'Advanced C++ Programming Styles and Idioms' describes a
roundabout way to implement such things in C++.  In Python, however, since
class creation looks like a function call, it would be just as easy to
implement this with (essentially) helper functions, e.g.,

def Expression(*args):
  "Construct an object of the Expression class or a subclass"
  if <blah blah blah>:
    return cLinearExpression(*args)
  elif <blah blah blah>:
    return cQuadraticExpression(*args)

class cExpression:
  blah blah blah

class cLinearExpression(cExpression):
  blah blah blah

this could easily be extended so that each potential subclass
"registers" itself with the virtual constructor, so that multiple
independent modules could extend a single virtual superclass
constructor.  In module expression.py:

Expression_subclasses = []
def Expression_register_subclass(subclass, test_fn):
  Expression_subclasses.append((subclass, test_fn))

def Expression(*args):
  for subclass, test_fn in Expression_subclasses:
    if test_fn(*args):
      return subclass(*args)
  return None

class cExpression:
  blah blah blah

and in module quadratic.py:

from expression import *

class cQuadraticExpression(cExpression):
  blah blah blah

def is_quadratic(*args):
  blah blah blah

Expression_register_subclass(cQuadraticExpression, is_quadratic)


Hope this helps.

-- 

  Dustin Mitchell
  dustin@cs.uchicago.edu
  dustin@ywlcs.org