[Numpy-discussion] vectorized function inside a class

Timothy Hochberg tim.hochberg at ieee.org
Wed Aug 8 11:54:18 EDT 2007


On 8/8/07, mark <markbak at gmail.com> wrote:
>
> I am trying to figure out a way to define a vectorized function inside
> a class.
> This is what I tried:
>
> class test:
>         def __init__(self):
>                 self.x = 3.0
>         def func(self,y):
>                 rv = self.x
>                 if y > self.x: rv = y
>                 return rv
>         f = vectorize(func)
>
>
> >>> m = test()
> >>> m.f( m, [-20,4,6] )
> array([ 3.,  4.,  6.])
>
> But as you can see, I can only call the m.f function when I also pass
> it the instance m again.
> I really want to call it as
> m.f( [-20,4,6] )
> But then I get an error
> ValueError: mismatch between python function inputs and received
> arguments
>
> Any ideas how to do this better?


Don't use vectorize? Something like:

def f(self,y):
    return np.where(y > self.x, y, self.x)

You could also use vectorize by wrapping the result in a real method like
this:

            _f = vectorize(func)
            def f(self, y):
               return self._f(self, y)

That seems kind of silly in this instance though.

-tim



-- 
.  __
.   |-\
.
.  tim.hochberg at ieee.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20070808/7a277262/attachment.html>


More information about the NumPy-Discussion mailing list