OO conventions

Claudio Grondi claudio.grondi at freenet.de
Wed Feb 1 18:07:37 EST 2006


Daniel Nogradi 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( )
> 
> Perhaps the real Image class of PIL doesn't have these methods
> exactly, but doesn't matter, my point is the way it works. Is it
> normal that instead of first creating an instance of a class, it
> starts right away with one its methods? I of course understand that
> the PIL people simply made a choice that their module works this way,
> period, but I'm just wondering if it wouldn't have been more "logical"
> to do it along the way of my first example.
> 
> I guess it's just a matter of convention or how the programmer feels
> like, but there are no conventions of this type? Which would be more
> pythonic? Or I shouldn't worry and it's totally up to the developer?
It's probably more up to the context than to the developer.

I can imagine, that the reason for not using
   image = Image()
is, that 'image' would be in a bad defined state suggesting to be an 
Image(), but after image = Image() it were actually not (yet) an image.

It makes sense to me, to have an actual image object with some pixel 
width and height and some color scheme and not only undefined empty 
container for an image. In another context the approach you describe is 
maybe more appropriate, but in case of an Image() object I can't see any 
advantage.

I don't know if there exist any conventions for how to handle such 
matters. For me Pythonic means it should be as I expect it intuitively. 
And my intuition tells me, that I need to define what image I want, when 
I create an Image object.

Maybe it would even be more appropriate to pass the definition of the 
image to the Image class using Image(fileObject) or Image(fileNameSpec) 
or Image(imageFormatAndSizeSpec), but I can imagine, that using 
different methods instead of detection of the type of parameter passed 
is probably less error prone making a good reason supporting the 
approach of using Image.open("bride.jpg") or Image.new(mode, size) for 
creation of an Image object when it is defined in different ways.

As the .new() and .open() methods are anyway there in order to be 
available for further image operations, why not using them directly in 
the process of creating Image() objects?

Claudio



More information about the Python-list mailing list