How can I override list methods to do vector addition and subtraction in python?
- by Bobble
I originally implemented this as a wrapper class around a list, but I was annoyed by the number of operator() methods I needed to provide, so I had a go at simply subclassing list. This is my test code:
class CleverList(list):
def __add__(self, other):
copy = self[:]
for i in range(len(self)):
copy[i] += other[i]
return copy
def __sub__(self, other):
copy = self[:]
for i in range(len(self)):
copy[i] -= other[i]
return copy
def __iadd__(self, other):
for i in range(len(self)):
self[i] += other[i]
return self
def __isub__(self, other):
for i in range(len(self)):
self[i] -= other[i]
return self
a = CleverList([0, 1])
b = CleverList([3, 4])
print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b)
c = a[:]
print('clone test: e = a[:]: a, e = ', a, c)
c += a
print('OOPS: augmented addition: c += a: a, c = ', a, c)
c -= b
print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a)
Normal addition and subtraction work in the expected manner, but there are problems with the augmented addition and subtraction. Here is the output:
>>>
CleverList does vector arith: a, b, a+b, a-b = [0, 1] [3, 4] [3, 5] [-3, -3]
clone test: e = a[:]: a, e = [0, 1] [0, 1]
OOPS: augmented addition: c += a: a, c = [0, 1] [0, 1, 0, 1]
Traceback (most recent call last):
File "/home/bob/Documents/Python/listTest.py", line 35, in <module>
c -= b
TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList'
>>>
Is there a neat and simple way to get augmented operators working in this example?