Don't be too hard on those who want class methods (Re: Python is wierd!)

Greg Ewing to_get_my_address at see.my.signature
Thu Jul 27 00:15:43 EDT 2000


Christian Tanzer wrote:
> 
> If you write code using classes as first-class objects, class
> variables and methods can be very useful.

This is a good point. Usually when people say that class methods
are not needed, they're talking about C++ or Java style static
methods. But Smalltalk-style class methods are a different
species altogether. In Smalltalk, a class is also an instance
(of class Class or some subclass thereof), so

   aClass frobulate: aBlivet

is dynamically dispatched on the runtime class of aClass,
just like any other message. There is no direct equivalent of
this in Python, because classes are not instances, they're a
different kind of object. The suggestion by Moshe Zadka:

> > class Function:
> >
> >       def __init__(self, func):
> >               self.func = func
> >
> >       def __call__(self, *args, **kw):
> >               return apply(self.func, args, kw)
> >
> > class SomeClass:
> >
> >       def class_method(a, b, c):
> >               return a+b+c
> >
> >       class_method = Function(class_method)

isn't quite the same thing, because there is no 'self'
in scope in the method which is bound to the receiving
class object (which might be a subclass of SomeClass,
so you can't just assume that it's SomeClass).

There are no doubt even more convoluted hacks that could
be used to fix that, but in 999,999,999 cases out of
a billion it's probably better to revise your design
so that you don't need class methods in the first place.

-- 
Greg Ewing, Computer Science Department, 
University of Canterbury, New Zealand
To get my email address, please visit my web page:
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list