On Feb 14, 2009, at 8:14 AM, Jean-Francois Moulin wrote:
> Hi,
>
> my first, probably very naive, question to the list.... I want to
> create an extension class with a method whose definition changes as a
> function of some test
> at the time of creation of the instance.
> Something like:
>
> cdef class Test:
>
> cdef int x, foo
I don't think this does what you think it does--it makes Test have
two attributes "x" and "foo"
>
> def __init__(self,foo):
>
> if foo>4:
> self.f = self.fn1
> else:
> self.f = self.fn2
>
> cdef fn1(self,x):
> return x
>
> cdef fn2(self,x):
> return 2 * x
>
>
> Is this possible, and if yes, how should I declare f?
Declare it as a c function pointer
cdef class Test:
cdef int (*f)(Test, int)
def __init__(self, foo):
if foo > 4:
self.f = self.fn1
else:
self.f = self.fn2
cdef int fn1(self, int x):
return x
cdef int fn2(self, int x):
return 2 * x
def test_f(self, x):
return self.f(self, x)
>>> a = Test(1)
>>> a.test_f(10)
20
>>> a = Test(100)
>>> a.test_f(10)
10
- Robert
_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev