Extending Python: rewriting a single method in C

Alex Martelli aleaxit at yahoo.com
Tue Mar 13 10:16:20 CET 2001


"Alexander Gavrilov" <agavrilov at home.com> wrote in message
news:2tfr6.26915$zV3.1982567 at news1.frmt1.sfba.home.com...
    [snip]
> > However, you cannot make a builtin function be a method of a
> class/instance.
> > Instead, you could write:
> >
> > from cmodule import fast_a, fast_b
> >
> > class fastKlass(Klass):
> > def a(self, int1, int2):
> > fast_a(self, int1, int2)
> > def b(self, int1, int2):
> > fast_b(self, int1, int2)
> >
>
> Actually, you can write the following:
>
> class fastKlass(Klass):
>     a = fast_a
>     b = fast_b

You can, but it will not work as intended if fast_a or fast_b
come from an extension module (coded in C or C++).  So-called
"builtin" functions (those coded in C) are not automagically
transformed into unbound methods when assigned as class attributes.

You _can_ request the transformation explicitly if you know
what you're doing...:

>>> class Y:
...     pass
...
>>> Y.a=new.instancemethod(cmodule.fast_a,None,Y)

Note that it can't be done within the body of Y since it needs
Y itself (the class-object) as an argument, and the class object
is not defined until AFTER the class-body is done executing.


Alex






More information about the Python-list mailing list