class methods vs instance methods (was Re: Why the 'self' argument?)

Alex Martelli aleax at aleax.it
Fri Sep 5 12:12:24 EDT 2003


vivek at cs.unipune.ernet.in wrote:
   ...
> The first argument in a class method is a reference to that class itself.

Yes, that's what defines CLASS methods (as opposed to ordinary, or
INSTANCE, methods).  But the original poster was not asking about class
methods, and you're not giving any examples of them -- I only see
instance methods.  I suspect a terminology problem -- you may be using
the term "class method" in a way that is totally inappropriate to
Python, where classes are first-level objects.


So -- in Python, you see...:

To make a class method you have to call on the classmethod built-in.  E.g.:

class Example(object):

    def instmeth(self): print 'Instance method of', self

    def clasmeth(cls): print 'Class method of', cls
    clasmeth = classmethod(clasmeth)

inst = Example()


Now you can call:

inst.instmeth()

or:

inst.clasmeth()
Example.clasmeth()

(both of these do exactly the same thing), but NOT:

Example.instmeth()

since an INSTANCE method, differently from a CLASS method,
needs to be passed the instance as the first argument, either
implicitly (by CALLING it on the instance) or explicitly
by passing it when calling the method on the class, as in:

Example.instmeth(inst)


Alex





More information about the Python-list mailing list