Concrete Factory Pattern syntax?

Austin Schutz tex at off.org
Thu Mar 19 18:52:13 EDT 2009


I have a fairly simple bit of code, something like:

# This should be importing the subclasses somehow, so that the factory
# can make them.
# import Parser.One
# import Parser.Two
# or.. from Parser import *?
class Parser():
   def parse:
	'Implemented only in subclass'

   def make_parser(which_parser):
       if(which_parser = 'one'):
         return One()
       else:
          return Two()

# import Parser?
class One(Parser):
   def parse:
       'one implementation'

class Two(Parser):
   def parse:
       'another implementation'

The problem I have is that I don't understand how to put this into
actual files in actual directories and have the interpreter do
something actually useful :-) . What I would like to do is something
like:

lib/
  Parser.py
  Parser/
      __init__.py (maybe?)
      One.py
      Two.py

But I'm not clear on how to structure the import statements. I'm a bit
of a newb wrt python, and I get any number of different errors depending
on how I arrange the import statements, everything from

AttributeError: 'module' object has no attribute 'make_parser'
to
ImportError: cannot import name
to
TypeError: Error when calling the metaclass bases

depending on how I use import. Nothing seems to be the correct
combination. Any help would be much appreciated!

Austin








More information about the Python-list mailing list