[Numpy-discussion] Vectorizing a class method
Wojciech Śmigaj
puddleglum at o2.pl
Wed Feb 14 13:27:31 EST 2007
Timothy Hochberg wrote:
> On 2/14/07, *Wojciech Śmigaj* <puddleglum at o2.pl
> <mailto:puddleglum at o2.pl>> wrote:
>> I have a question about the vectorize function. I'd like to use it to
>> create a vectorized version of a class method. I've tried the following
>> code:
>>
>> from numpy import *
>>
>> class X:
>> def func(self, n):
>> return 2 * n # example
>> func = vectorize(func)
>>
>> [...]
> I think you want staticmethod. Something like:
>
> class X:
> def f(x):
> return 2*x
> f = staticmethod(vectorize(x))
>
> However, I don't have a Python distribution available here to check
> that. If that doesn't work, as search on staticmethod should get you to
> the correct syntax.
>
> I'll just note in passing that if your function is composed of
> completely of things that will operate on arrays as is (as your example
> is), then vectorizing the function is counter productive. However, your
> real code may well need vectorize to work.
Thank you for your answer. I see now that my example was oversimplified.
In reality, the method func() accesses internal data of the object, so
it cannot be made a staticmethod. In addition, it does not operate on
the array as a whole: basically, it does calculations according to some
formula if n != 0, and to another one otherwise. Perhaps both parts
could be merged in some intelligent way, but right now I want to make
the program work, and optimization will be done later. And vectorize is
a very nice and quick way of making functions accept arrays, even if it
is not super-efficient.
Best regards,
Wojciech Smigaj
More information about the NumPy-Discussion
mailing list