OO conventions

Terry Hancock hancock at anansispaceworks.com
Wed Feb 1 20:09:03 EST 2006


On Wed, 1 Feb 2006 23:40:37 +0100
Daniel Nogradi <nogradi at gmail.com> wrote:
> I'm relatively new to object oriented programming, so get
> confused about its usage once in a while. Suppose there is
> a class Image that has a number of methods, rotate, open,
> verify, read, close, etc. Then to use this class my
> natural guess would be to have something like
> 
> image = Image( )
> image.read( "myfile.jpg" )
> image.rotate( )
> image.close( )
> 
> But now it turns out that the PIL module uses this as
> 
> image = Image.open( "myfile.jpg" )
> image.verify( )
> image.rotate( )
> image.close( )

That's because that *isn't* object oriented.  PIL provides
an "open" *function* that opens a file containing an image
and *returns* an Image object.  The two "Image" usages are
not the same. I personally think he should've named the
module "Imaging" or something, to make this clearer, but you
can of course fix this in the import (I frequently have had
to call it PIL_Image or something, because of collisions
with other modules or objects named "Image").

What Lundh is modeling this on is not standard OOP thinking,
but rather the standard way of opening files in Python.

Or you could say he's using a "factory function".

I think it is actually not bad style, because in fact, he's
drawing attention to the fact that the image is NOT "an
object initialized by the string 'myfile.jpg'", but is
rather a function loading data from a file called
'myfile.jpg' and creating a PIL Image object from *that*.

Remember, programming is an art, not a science.
"Object-oriented style" is a subjective and fuzzy
aesthetic term, and what is "most clear" depends on what
you've seen before, and what you're trying to be clear
about.

Cheers,
Terry


-- 
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com




More information about the Python-list mailing list