How to store a function pointer in class?
Gordon McMillan
gmcm at hypernet.com
Thu Jan 20 17:12:04 EST 2000
Sami Hangaslammi writes:
> Justin Sheehy <dworkin at ccs.neu.edu> wrote in message
> news:vnd66wo1nz2.fsf at betelgeuse.ccs.neu.edu...
> > You could store the function inside a mutable class data member.
>
> Yeah, I figured this out myself, but it still seems like an
> unneccessary and ugly hack.
Perhaps if you understood the mechanics, it would not appear
that way.
obj.method(args)
becomes (in psuedo code):
apply(getattr(obj, method), args)
For instance objects, getattr first checks in the instance, then
in instance.__class__, then a walk of the bases. It finds a
function object, (unless it's actually on the instance, but that's
rare). This is, on the fly, transformed into an unbound method,
which (when it trickles back to the instance) becomes a
bound method. This can be called (and the "self" parameter is
safely squirreled away in the binding).
If you want things on the class that _stay_ function objects,
you'd need some way to distinguish those which _should_ be
transformed from those that _shouldn't_. No such flag exists,
and no such hook exists.
People ask for this regularly. But there are those (like
yourself) who want to be able to get a plain old function, and
there are those who want "class methods", ie, methods bound
to the class object, not the instance object.
- Gordon
More information about the Python-list
mailing list