calling subclass constructor question
Steven Bethard
steven.bethard at gmail.com
Mon Jun 20 02:39:42 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.
Still not sure I understand you. How are you determining which new type
of plot to create? If I'm an instance of class PlotA, and the user asks
me to create create a new Plot, is it always another instance of class
PlotA, or could it be an instance of another class?
If the former, you can use a classmethod, e.g.:
class Plot(object):
@classmethod
def new(cls, ...):
result = cls(...)
# maybe modify result some more
return result
If the latter, this doesn't sound like something that should be a method
of an instance. It sounds more like a factory function. Why not just
make it a module-global function, e.g.:
def newPlot(...):
# determine which kind of Plot object to create
...
if ...:
return PlotA(...)
...
A method signature of the method you want to write would help a lot...
STeVe
More information about the Python-list
mailing list