Access to C functions from a python class using self ?

Bengt Richter bokr at oz.net
Mon Dec 30 12:51:10 EST 2002


On Mon, 30 Dec 2002 12:59:16 +0100, christophe grimault <christophe.grimault at novagrid.com> wrote:

>Hi there,
>
>I've been looking to 'ext & emb python', swig, cxx, ... for quite some 
>time now, and I still can't figure out how to do the kind of stuff 
>explained below...
>
>I define a class in python, let's say this simple class, just for the 
>purpose of discussion :
>
>class Vector:
>    def __init__(self, x1, x2, x3):
>        self.x1, self.x2, self.x3 = x1, x2, x3
>
>    def sum(self):
>        return self.x1 + self.x2 + self.x3
>
>Now, I find that sum is slow, and I want to speedup things by replacing 
>sum by a call to C.
I suspect your best options will vary with your larger context. I.e.,
when you "find that sum is slow," it was probably in a hot loop doing
sum many times, or you wouldn't notice. So there is much else going on,
and the actual summing may be the least of it (unless x1,x2,x3 are classes
that define __add__ and contain large amounts of data to "add.") I'm
assuming the x's are numbers.

So what kind of loops do you have making use of this class Vector?

>Looking at the manual, I can write something like:
>
>static PyObject *sum( PyObject *self, PyObject *args )
>
>and  the manual tells me how to access elements passed in args, but does 
>not tell how to access elements (in fact attributes) of self. How can I 
>retrieve self.x1, self.x2, and self.x3 as defined in the python class 
>from *self passed to the C function ?
>
>The goal for me is to create classes quickly in Python. These classes 
This may become a goal, but IME it is ususally premature to say "the" goal
while referring to a particular implementation strategy ;-)

>have, say, a constructor and 5 to 30 methods. The object itself is quite 
>complex (lots of attributes of different types) and only one or two 
>method need very high speed and thus, must call C.
I suspect there will be more than one way to accomplish this.

>
>And i want to avoid passing all the attributes needed by those C calls 
>by increasing the *args !
>
Ditto.

Regards,
Bengt Richter



More information about the Python-list mailing list