I have a series of classes which can be created by optionally passing a parameter, or if ommited, it will use a default data structure. All the classes work in the same way, thus:
class square(object):
_vertices = [ (0, 0), (0, 10), (10, 10), (10, 0) ]
def __init__(self, vertices=_vertices):
# more stuff ...
class triangle(object):
_vertices = [ (0, 0), (5, 10), (10, 10) ]
def __init__(self, vertices=_vertices):
# more stuff ...
# ... more classes
I also have a factory function which takes a string and creates an appropriate object
def create_shape(key)
if key == 'square':
return square()
elif key == 'triangle':
return triangle()
Though naturally, this does not allow me to pass the vertices parameter
shape1 = create_shape('square') # OK, basic creation
shape2 = create_shape('triangle', my_own_vertices) # Not OK, param 2
# can't go through factory
My way round this was to embellish the factory as follows, although, to me, this seems a very clumsy way of going about things.
def create_shape(key, vertices=None):
if key == 'square':
return square(vertices) if vertices else square()
elif key == 'triangle':
return triangle(vertices) if vertices else triangle()
In essence, I simply want to pass through an optional parameter without the top level (create_shape) knowing what the default should be. Is there a clearer / simpler / more pythonic way of doing this? I've looked at other questions / answers but nothing seemed much better than the above.