what *is* a class?

Jeff Epler jepler at unpythonic.net
Mon Jun 17 10:35:26 EDT 2002


On Mon, Jun 17, 2002 at 12:40:07PM +0200, Uwe Mayer wrote:
> I had to distinguish between creating the object model and actually
> reading the file in. Thus I decided to use the constructor for creating
> the object model and provide a parse() method. I didn't like writing:
> 
> f = file('dummy.avi','rb')
> avi = RIFF(<specify format>)
> avi.parse(f)
> 
> instead I wanted to write:
> 
> avi = RIFF(<specify format>).parse(f)
> 
> but then of course parse() must return an instance object.
> On the one side all parse() methods must explicitly "return self" (which
> is not nice). On the other side from the semantics I thought it was ok
> for parse to return an instance object of RIFF.

This is not the Pythonic style.  Even when it would sometimes be
convenient, methods do not tend to return "self".  That's why these
don't work:

    # Iterate the sorted list
    for item in l.sort(): ...

    # Create and pack a widget
    x = Label(text="Wibble").pack()

    # Dump two objects to a pickle
    p = pickle.Pickler()
    p.dump(obj1).dump(obj2)

One motivation for this is that if list.sort returns None, nobody
will write
    for item in l.sort():
thinking that a copy of l is sorted.  It'll immediately blow up.  I did
a quick Google search to try to find a clear statement of this
principle, but I didn't find it.  However, I tend to agree with the
idea that methods called for their side-effects should generally not
return the object.  This makes it clear when a method mutates the object
and when it returns a mutated object, and this distinction is often
quite important.

Jeff





More information about the Python-list mailing list