what *is* a class?

Douglas Zongker dougz at cs.washington.edu
Sun Jun 16 21:21:14 EDT 2002

Uwe Mayer <merkosh at hadiko.de> wrote:
: i've got an object 'Group'. i instanciate it by calling, f.e.
: g = Group()

: what actually does Group() return and is there any way to get hold of 
: that again?

"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.



More information about the Python-list mailing list