Does Python have Class methods

Alex Martelli aleaxit at yahoo.com
Sat May 12 00:29:37 CEST 2001


"Magnus Lie Hetland" <mlh at idi.ntnu.no> wrote in message
news:9dhn0p$ktf$1 at tyfon.itea.ntnu.no...
> "Alex Martelli" <aleaxit at yahoo.com> wrote in message
> news:9d9fk70gmr at news1.newsguy.com...
> >
> > Right, but that supports "static methods" a la C++ rather than "class
> > methods" a la Smalltalk.  Another alternative for "static methods" is at
> > http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52304, for
> > example.  Thomas Heller has also put up a Cookbook recipe, at
> > http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/52311,
> > which exemplifies how to support "real" (Smalltalk-ish) class methods.
> >
> >
> > Alex
>
> Thought I had answered this, but it seems my message didn't make it...
> So I try again:
>
> What about something like this:
>
>    def double(self, x): return x*2
>
>    class Math:
>        double = double
>
> This works like a class method, doesn't it?

...except that you have to instantiate Math to be able to CALL it.  You
can't call Math.double(x) [it needs two arguments and ignores the first
one] and to call Math.double(x,y) x needs to refer to an instance of
Math (the method ignores it, but Python checks that at runtime and
will raise an exception otherwise).  Pretty annoying.  If you use the
simple Callable wrapper in my above-quoted recipe,

    class Math:
        def double(x): return x*2
        double = Callable(double)

NOW Math.double(x) IS callable, with just the single argument it
needs.  And if m happens to be an instance of class Math, then
m.double(x) is fine, too.


Alex






More information about the Python-list mailing list