Ignore this page

Honest, if you're the sort of reader I had in mind when writing all this then you should go back to the main page now - this page is just "for the record", for Python programmers who noticed that I did a bad thing when I wrote Vector.__repr__.

Ok, you're still reading. "For the record", if we have

x = Vector([1, 2, 3])
then x.__repr__ is not supposed to return "[1, 2, 3]" the way it does. repr(x) is supposed to be a string that allows one to reconstruct x; in this example that means that x.__repr__() should return the string "Vector([1, 2, 3])", not "[1, 2, 3]". It would be ok for x.__str__() to return "[1, 2, 3]", and if I'd simply called that method __str__ instead of __repr__ then all the Vector examples on the page would work the same as they do.

The reason I did it the way I did was to make the code for Matrix as simple as possible; if I'd had x.__repr__() return the right thing then later when I say

x = Matrix([[1, 2], [3, 4]])
print x + x
I'd get "[Vector([2,4]), Vector([6, 8])]" instead of the "[[2, 4], [6,8]]" that I wanted. (Of course I could fix that by giving Matrix an appropriate __str__() method... that's exactly what I didn't want to worry about here.)

As long as I'm talking about aspects of the examples that are not quite right, Vector.__add__ should really return self.__class__(data) instead of Vector(data). The two are the same when I add actual Vectors, but later when I say make Matrix a subclass of Vector I want the sum of two Matrix objects to be a Matrix instead of a Vector (so that when I give Matrix an appropriate __mul__ method it will be invoked when I say

x = Matrix(whatever)
print (x + x)*(x + x);
right now the sum of two Matrix objects is a Vector, and things are not going to work.)

If you're still reading even though you're not a Python guy: If I rewrite Vector.__add__ to return self.__class__(data) instead of Vector(data) that means it returns Vector(data) if self happens to be a Vector and Matrix(data) if self is a Matrix. The fact that I can do this is an example of the wonderful "introspection" that Python objects allow (it might be regarded as a trivial example of what Raymond is calling "metaclass" programming.)