[Python-Dev] Class Methods

Michel Pelletier michel@digicool.com
Fri, 20 Apr 2001 10:50:15 -0700 (PDT)


On Fri, 20 Apr 2001, Thomas Heller wrote:

> > Here's something to start the fight ;-) ...
> >
> > 1) What would you do with class methods that you cannot do with
> >    e.g. globals and functions ?
>
> I will write up a concrete example I have and post it later.

There are a number of reasons why I'm all for Class attributes in general.
For example, right now a class object cannot assert an interface.  Sure,
a class can say:

class Foo:

  __implements__ = Bar  # instances implement Bar

but that is an assertion for the instances, not the *class itself*.
Currently, you have to do the ugly hack:

class Foo:

  __class_implements__ = FooFactory # the class implements
                                    # FooFactory.

We've done things like the above in several places in our underground
component elaboration.  Not having class methods introduces many little
wrinkles in the Python object model that have to be worked around.  I can
imagine, for example, wanting to define an __reduce__, or __init__ for a
class object, which is not possible now.

> Look into the motivation for the Prototype Pattern in the GOF
> book, or even better in the discussion of this pattern in the
> 'Design Pattern Smalltalk Companion' book.
>
> This pattern is not needed if classes are 'first class' objects.
>
> >
> > 2) How would you determine which methods are class-only methods and
> >    which are one usable by instances ?
> This is one of the issues which has to be resolved. I have no proposal
> at the moment. (Maybe function attributes can help here?)

I always thought along the lines of saying Class.instanceAttribute('foo')
in the place of what is now said Class.foo.  This would, of course, break
code, but the warning and back to the future features mitigate most of
that risk.

> >
> > 3) If you don't like globals (see 1), wouldn't it be possible to
> >    store the state you want to manipulate using class methods
> >    in some other context object ?
> I want the class methods (for example) to create and manipulate
> this 'context object'. This object, however, belongs into the class...
>
> What I want to avoid is
>
>   class X(...):
>       ....
>   initialize(X)

Yes! We use this monstrosity a lot in Zope.

-Michel