[Numpy-discussion] Vectorizing a class method

Timothy Hochberg tim.hochberg@ieee....
Wed Feb 14 11:10:38 CST 2007


On 2/14/07, Wojciech Śmigaj <puddleglum@o2.pl> wrote:
>
> Hi,
>
> 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)
>
> Now, when I declare an instance of the class X and invoke func() as an
> unbound method, it works:
>
>    x = X()
>    print X.func(x, [1, 2])  # output: [2 4]
>
> But an attempt to invoke it "normally", i.e. like
>
>    print x.func([1, 2])
>
> fails with the message
>
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "/usr/lib/python2.4/site-packages/numpy/lib/function_base.py",
> line 823, in __call__
>      raise ValueError, "mismatch between python function inputs"\
> ValueError: mismatch between python function inputs and received arguments
>
> It seems that in this case the class instance (x) isn't passed to the
> vectorize.__call__() method, and as a result the number of arguments
> does not agree with what this method expects.
>
> Does anybody have an idea of how to do it correctly? As a workaround, I
> can write a wrapper function on the module level, which can be
> vectorized without problems, and call it from inside the class---but it
> looks ugly and is tedious given that I have multiple functions to be
> handled in this way.



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.


Thanks in advance for any help,
> Wojciech Smigaj
> _______________________________________________
> Numpy-discussion mailing list
> Numpy-discussion@scipy.org
> http://projects.scipy.org/mailman/listinfo/numpy-discussion
>



-- 

//=][=\\

tim.hochberg@ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20070214/1daeaf0d/attachment.html 


More information about the Numpy-discussion mailing list