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()
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()
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.
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?)