# [Numpy-discussion] Unexpected output using numpy.ndarray and __radd__

Mark Hoffmann Mark.Hoffmann at dk.manbw.com
Fri Dec 15 09:42:24 CST 2006

```Hi,

The following issue has puzzled me for a while. I want to add a
numpy.ndarray and an instance of my own class. I define this operation
by implementing the methods __add__ and __radd__. My programme
(including output) looks like:

#!/usr/local/bin/python

import numpy

class Cyclehist:
def __init__(self,vals):
self.valuearray = numpy.array(vals)

def __str__(self):
return 'Cyclehist object: valuearray = '+str(self.valuearray)

def __add__(self,other):
print "__add__ : ",self,other
return self.valuearray + other

def __radd__(self,other):
print "__radd__ : ",self,other
return other + self.valuearray

c = Cyclehist([1.0,-21.2,3.2])
a = numpy.array([-1.0,2.2,-2.2])
print c + a
print a + c

# ---------- OUTPUT ----------
#
# addprob \$ addprob.py
# __add__ :  Cyclehist object: valuearray = [  1.  -21.2   3.2] [-1.
2.2 -2.2]
# [  0. -19.   1.]
# __radd__ :  Cyclehist object: valuearray = [  1.  -21.2   3.2] -1.0
# __radd__ :  Cyclehist object: valuearray = [  1.  -21.2   3.2] 2.2
# __radd__ :  Cyclehist object: valuearray = [  1.  -21.2   3.2] -2.2
# [[  0.  -22.2   2.2] [  3.2 -19.    5.4] [ -1.2 -23.4   1. ]]
# addprob \$
#
# ----------------------------

I expected the output of "c+a" and "a+c" to be identical, however, the
output of "a+c" gets nested in an elementwise fashion. Can anybody
explain this? Is it a bug or a feature? I'm using Python 2.4.4c1 and
numpy 1.0. I tried the programme using an older version of Python and
numpy and there the result of "c+a" and "a+c" are identical.

Regards,

Mark Hoffmann

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20061215/4db77dc1/attachment-0001.html
```

More information about the Numpy-discussion mailing list