[Tutor] creating a subclass from superclass without __init__

Matt Gregory matt.gregory at oregonstate.edu
Fri Aug 24 22:03:41 CEST 2012


On 8/24/2012 12:01 PM, Steven D'Aprano wrote:
> That's not a use-case. A use-case is a real-world problem that you
> are trying to solve. You have skipped the problem and jumped straight
> to what you think is the solution: "create a subclass which can't be
> instantiated directly".
>
> I can't imagine any problem where the solution to the problem depends
> on whether or not you instantiated a subclass using:
>
> Spam(*args)
>
> or
>
> SpamMaker.make(*args)

Clearly my explanation was pretty bad.  I'll start with my real-world 
problem instead, although it may be outside the scope of this list (thus 
my lame attempt to abstract it).

There are two classes of interest in GDAL - a Dataset which typically 
describes a geospatial raster file and Band which described a single 
band from the Dataset.  gdal.Band just raises an AttributeError within 
__init__, but a gdal.Band instance can be created using 
gdal.Dataset.GetRasterBand(bandNum).

I had wanted to create additional methods on gdal.Band that would allow 
some GIS type operations (e.g. overloading __add__), thus I thought I 
would need a subclass of gdal.Band.  So I was unsure of how to get an 
instance of my subclass when the only way I knew how to create an 
instance of the superclass (gdal.Band) was through the call to 
GetRasterBand().

Does that make any sense in relation to my contrived example?  In my 
example, I didn't really want to create a Spam instance from the SubSpam 
__new__, I just didn't know how to return a SubSpam instance that was 
forced to go through SpamMaker.make_spam().

matt



More information about the Tutor mailing list