calling subclass constructor question

D H d at e.f
Sun Jun 19 22:35:50 EDT 2005


In Han Kang wrote:
> So each of the sub classes plots a different type of graph.  The 
> superclass defines methods that are the same for all the plots.  I want 
> to be able to pick some points and be able to generate a more plots.  
> What I was wondering if I could define in a method in the superclass of 
> an object the ability to make a brand new subclass (new plot).  So 
> basically, one plot makes another plot, but it'd be nice if i could put 
> all the code in the superclass.

Right, I agree with Steven, that you are probably wanting something like 
the factory pattern.  Here's something modified from Steven's example 
more like what you are asking for:

class Plot(object): #you need to subclass object to get __subclasses__

     @staticmethod
     def getplot(name):
         return [plot for plot in
                 Plot.__subclasses__() if plot.__name__ == name][0]()


class LinePlot(Plot):
     pass

class BarGraph(Plot):
     pass

lp = Plot.getplot("LinePlot")

bar = Plot.getplot("BarGraph")

See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900



More information about the Python-list mailing list