[Python-Dev] Class Methods

Alex Martelli aleaxit at yahoo.com
Sat Apr 21 09:52:49 EDT 2001


"Thomas Heller" <thomas.heller at ion-tof.com> wrote in message
news:9brq3j$app53$1 at ID-59885.news.dfncis.de...
    [snip]
> > I'm not sure, maybe use the class object X itself?  That object
> > isn't available in the class body.  For example, initialize(X)
> > could among other things enregister class object X with any
> > appropriate registrars, as above.  But that may not be what
    [snip]
> >  (and I don't understand why
> > one would need to avoid the example usage I proposed,
> > anyway).
> Which example?

Enregistering a class object with any appropriate registrars
was the sample usage that I proposed in the above-quoted
text, which needs to use the class-object itself, and thus
can't be in the class body (as the class-object does not yet
exist as the class body is being executed) but could well be
in a separate function to be called with the class object as
its argument (probably better than inline, as it's likely that
more than one class object may need to be registered in
similar ways).  Doesn't seem to me this needs to be avoided.

A completely different issue might be one having to do with
inheritance.  Inheritance currently only affects instances; a
base class's method gets a self argument, an instance, and
may examine/use/set any attribute of that instance (which
may well come from a subclass); the class's body, however,
is only executed when the class statement itself is, and
taking inheritance into account at that point is impossible
for the base class (only one base-class object exists, whoever
will inherit it) and not necessarily easy for subclasses (as
the class-object doesn't yet exist as their body executes).

Say I want to ensure that any class object that has an
attribute named 'floop' also gets one named 'ploof' that
is its .reverse().  That's easy in a separate function:

def ensurePloof(X):
    if X.hasattr('floop'):
        X.ploof = X.floop.reverse()

This takes normal derivation into account, etc.  But I
don't know how to do it, except by explicitly calling
ensurePloof(X) on each class X needing this kind of
initialization after X is created.  If it was an issue of
_instance_ attributes, rather than _class_ ones, I'd
have options (__getattr__ in a mixin, etc).


Alex






More information about the Python-list mailing list