Simplish thing if you're writing a bunch of code, but don't want a more complicated vector library...
class V(tuple):
'''A simple vector supporting scalar multiply and vector add'''
def __new__ (cls, *args):
return super(V, cls).__new__(cls, args)
def __mul__(self,s):
return V( *( c*s for c in self) )
def __add__(self,s):
return V( *( c[0]+c[1] for c in zip(self,s)) )
def __repr__(self):
return "V" + super(V, self).__repr__()
# As long as the "vector" is on the left it just works
xaxis = V(1.0, 0.0)
yaxis = V(0.0, 1.0)
print xaxis + yaxis # => V(1.0, 1.0)
print xaxis*3 + yaxis*5 # => V(3.0, 5.0)
print 3*xaxis # Broke, => (1.0, 0.0, 1.0, 0.0, 1.0, 0.0)
The "V" instances otherwise behave just like tuples. This requires that the "V" instances are all created with the same number of elements. You could add, for example, to __new__
if len(args)!=2: raise TypeError('Must be 2 elements')
to enforce that all the instances are 2d vectors....