creating one of a family of classes

Quinn Dunkan quinn at cruzeiro.ugcs.caltech.edu
Thu Dec 2 22:21:15 EST 1999


On Thu, 02 Dec 1999 20:11:39 -0500, Roy Smith <roy at popmail.med.nyu.edu> wrote:
>I want to have a family of classes which are all subclasses of a common
>ancestor.  For the sake of a simple example, let's say I have a class
>polygon, with subclasses triangle, square, pentagon, and hexagon.
>
>I want to be able to call the top-level creator, and have it return an
>object of the appropriate subclass based on the argument I give it.  For
>example:
>
>p = polygon ([(1,2), (4,5), (0,4)])
>
>would return an object of class triangle and
>
>p = polygon ([(1,2), (4,5), (0,4), (3,4)])
>
>would return an object of class square.  Is such a thing possible?

There's no need to have the superclass do this, just make a function.  In
fact, if you did have the superclass do it, and the subclasses' __init__
wanted to call their superclass... that's a problem.

def try_to_figure_out_what_kind_of_polygon_it_is_from_args_and_return_it(a):
    if len(a) == 3:
        return apply(Triankle, a)
    elif len(a) == 4:
        return apply(Skware, a)

And as for the wisdom of doing this in the first place... well, I don't
know the circumstances :)




More information about the Python-list mailing list