what *is* a class?
Uwe.Mayer at ifib.uni-karlsruhe.de
Mon Jun 17 12:40:07 CEST 2002
Douglas Zongker wrote:
> "Group()" creates a new object which is an instance of the class
> Group. It calls the object's initializer ("__init__" method), then
> returns the newly created object.
> : i want to write a method which returns the instance, so that f.e. the
> : following is possible:
> : g = Group()
> : g2 = g.foobar()
> : g2 is g
> : so that g2 is identical to g.
> : any idea?
> class Group:
> def __init__( self ):
> print 'creating instance'
> def foo( self ):
> print 'in the foo method'
> return self
> >>> g = Group()
> creating instance
> >>> g2 = g.foo()
> in the foo method
> >>> g2 is g
> Note that there's usually no reason for a method (such as "foo") to
> return the self object, because the caller should already have the
> object to call the method in the first place. I could leave "return
> self" out of the definition of "foo", and just write:
> g = Group()
> g2 = g
> The result would be the same.
I am very sorry. Of course I tried that, returning self, but perhaps I
called: g2 = g.foo instead of g2 = g.foo()
The reason why I wanted that was for lazyness. I am writing classes
which should provide random access to arbitrary binary file formats with
a special focus on RIFF.
I wanted to create an object model of the file (without actually reading
all of it - especially skipping the large data chunks).
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>)
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.
What do you think?
Thanks for your help!
More information about the Python-list