[Numpy-discussion] Overload binary operators with custom array type
Adam Jenkins
adam at thejenkins.org
Fri Jan 12 16:43:33 CST 2007
Travis Oliphant <oliphant.travis <at> ieee.org> writes:
>
> Adam Jenkins wrote:
> > I just tried it, and it does solve the problem for the
> > mathematical operators like + and -, but doesn't seem to work for
> > the comparison operators. That is, if I write
> >
> > lhs < rhs
> >
> > where lhs is a numpy.ndarray and rhs is a myarray, numpy still
> > treats rhs as a scalar and tries to compare each element of lhs to
> > rhs, even though I set myarray.__array_priority__. Is this
> > intentional that the comparison operators ignore
> > __array_priority__, or just a bug in ndarray?
>
>
> Probably could be considered a bug.
>
> What does
>
> less(lhs, rhs)
>
> do?
It does the same thing, calls rhs.__gt__ on each element of lhs. Hmm,
I just tried numpy.add(lhs, rhs), and that returns NotImplemented,
whereas "lhs+rhs" results in rhs.__radd__(lhs) being called. So
"lhs<rhs" behaves the same as numpy.less(lhs,rhs), but "lhs+rhs" and
numpy.add(lhs,rhs) behave differently.
Here's a sample program which demonstrates all this. I'm using python
2.4.3 and numpy 1.0.1.
Adam Jenkins
test.py
-----------
import numpy
class myarray(object):
def _get_array_priority(self):
print "myarray.__array_priority__"
return 20
__array_priority__ = property(_get_array_priority)
def __add__(self, other):
print "myarray.__add__(%s)" % (other,)
return 1
def __radd__(self, other):
print "myarray.__radd__(%s)" % (other,)
return 1
def __lt__(self, other):
print "myarray.__lt__(%s)" % (other,)
return True
def __gt__(self, other):
print "myarray.__gt__(%s)" % (other,)
return True
lhs = numpy.array([1,2,3])
rhs = myarray()
print "lhs+rhs=%s\n" % (lhs + rhs,)
print "add(lhs, rhs)=%s\n" % (numpy.add(lhs, rhs),)
print "lhs<rhs=%s\n" % (lhs < rhs,)
print "less(lhs, rhs)=%s\n" % (numpy.less(lhs, rhs),)
More information about the Numpy-discussion
mailing list