Return to Home Page
      Blog     Consulting     Seminars     Calendar     Books     CD-ROMS     Newsletter     About     FAQ      Search
 

why not just:

def shapeGen(n):
types = Shape.__subclasses__()
for i in range(n):
yield random.choice(types)()

for shape in shapeGen(7):
shape.draw()
shape.erase()

f  e  x


try again...


def shapeGen(n):
  types = Shape.__subclasses__()
  for i in range(n):
    yield random.choice(types)()

for shape in shapeGen(7):
  shape.draw()
  shape.erase()
f  e  x


To be closer to the original, and allow shapes to be created by name, you could use the code below (warning: untested code).


# add all shape subclasses above here

_shapes = {}
for s in Shape.__subclasses__:
    _shapes[s.__name__] = s

def ShapeFromName(name):
    return _shapes[name]()

or perhaps:


def ShapeFromName(name, *args, **kw):
    return _shapes[name](*args, **kw)

I'm afraid that, as far as I can see, this factory example is just an obfuscated way to created shapes by name. Ican't see much difference between these two:


s = ShapeFromName('Circle')
s = Circle()

This is probably my fault, but maybe you could explain it more.

f  e  x


1) Can you clarify why factory() should be a staticmethod rather than an __init__ method which dynamically redirects the call to the constructor of the required class (using exec() if necessary) ?
Or is that just a migrated limitation of Java? What are the implications of either on recursion inside the factory() method?
1b) Is it an abuse to put factory() code in the __init__() method?
What code (if any) should be contained in the __init__() method of a factory class? (I have seen registering of handlers inherited from parent classes, for recursion).

2) Why are calls to explicit class constructors shown instead of the more intuitive dynamic exec with error-trapping?


try:
  return eval(type + "()")
except:
  sys.stderr.write("Error: Type %s does not exist" % type)

(Again it looks like this is just a Java hangover?)
f  e  x



Add your comment below. Use an empty line between each paragraph. Paragraphs will be automatically formatted, and single carriage returns will be respected. Use <code> to begin a code block, and </code> to end a code block. Your email address will not be visible to spam harvesters or used in any way except to contact you with further questions.

Your Email Address:

Search     Home     WebLog     Consulting     Seminars     Calendar     Books     CD-ROMS     Newsletter     About     Contact     Site Design     Server Maintenance     Powered by Zope
©2007 MindView, Inc.