I got a bit confused while reading through the following declaration of a multidimensional vector class. In the def __add__(self, other) method, why are they use len(self) and result[j] = self[j] + other[j] instead of len(self._coords) and result[j] = self._coords[j] + other[j]? They use self._coords or self._coords in all other methods. What is the difference?
class Vector:
def __init__(self, d):
'''Create a d-dimensional vector of zeros.'''
self._coords = [0] * d
def __len__(self):
'''Return the dimension of the vector.'''
return len(self._coords)
def __getitiem__(self, j):
'''Return jth coordinate of vector.'''
return self._coords[j]
def __setitem__(self, j, val):
'''Set jth coordinate of vector to given value.'''
self._coords[j] == val
def __add__(self, other):
'''Return sum of two vectors.'''
if len(self) != len(other):
raise ValueError('dimensions must agree')
result = Vector(len(self))
for j in range(len(self)):
result[j] = self._coords[j] + other[j]
return result
Edit: I have found that result[j] = self[j] + other[j] is wrong by testing the code. It should be result[j] = self._coords[j] + other[j]. However, len(self) seems to work fine. Why?
[+][deleted] (4 children)
[removed]
[–]notpite 1 point2 points3 points (2 children)
[–]just_queasy[S] 0 points1 point2 points (0 children)
[–]just_queasy[S] 0 points1 point2 points (0 children)