OO conventions

Blair P. Houghton blair.houghton at gmail.com
Thu Feb 2 20:00:26 EST 2006


Image would be a superclass to JPGImage, BMPImage, PNGImage, etc...

But which to use could only be determined AFTER opening the file,
because "file.jpg" doesn't have type JPG, it has type string and
semantic value "maybe a jpeg file or maybe something misnamed as a jpeg
file".

So Image.open(filename) seems right as a factory function that opens
the file, figures out what it really is, constructs the appropriate
subclass object (likely by passing a string to the constructor, e.g.,
JPGImage(filename)), and returns the object via the superclass type.
The caller can then either check a flag in the superclass to see what
type the subclass is, or just assume it's the right type of image for
the filename extension (or does Python have RTTI? I don't recall if
I've seen it, yet...).

Though if the filename doesn't match the content, someone should raise
an exception...

But this means that Image.open(filename) is a static method of the
superclass, not requiring instantiation.  Image(string) could easily
default to assuming string is a filename, doing the same work as
Image.open(filename), though it would at least partially construct an
Image instance each time it's called, which isn't what you want.
Image.open(filename) defined as a static method (wait...is that
possible in Python? I hate being the newbie) would not do any
constructing until after it knew what to construct.

--Blair




More information about the Python-list mailing list