/Demo/classes/Vec.py

http://unladen-swallow.googlecode.com/ · Python · 54 lines · 34 code · 16 blank · 4 comment · 1 complexity · f33cd1a110e8ab25e4cb14b955f39f93 MD5 · raw file

  1. # A simple vector class
  2. def vec(*v):
  3. return Vec(*v)
  4. class Vec:
  5. def __init__(self, *v):
  6. self.v = list(v)
  7. def fromlist(self, v):
  8. if not isinstance(v, list):
  9. raise TypeError
  10. self.v = v[:]
  11. return self
  12. def __repr__(self):
  13. return 'vec(' + repr(self.v)[1:-1] + ')'
  14. def __len__(self):
  15. return len(self.v)
  16. def __getitem__(self, i):
  17. return self.v[i]
  18. def __add__(self, other):
  19. # Element-wise addition
  20. v = map(lambda x, y: x+y, self, other)
  21. return Vec().fromlist(v)
  22. def __sub__(self, other):
  23. # Element-wise subtraction
  24. v = map(lambda x, y: x-y, self, other)
  25. return Vec().fromlist(v)
  26. def __mul__(self, scalar):
  27. # Multiply by scalar
  28. v = map(lambda x: x*scalar, self.v)
  29. return Vec().fromlist(v)
  30. def test():
  31. a = vec(1, 2, 3)
  32. b = vec(3, 2, 1)
  33. print a
  34. print b
  35. print a+b
  36. print a-b
  37. print a*3.0
  38. test()