vector.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #!/usr/bin/env python3
  2. """
  3. A demonstration of classes and their special methods in Python.
  4. """
  5. class Vec:
  6. """A simple vector class.
  7. Instances of the Vec class can be constructed from numbers
  8. >>> a = Vec(1, 2, 3)
  9. >>> b = Vec(3, 2, 1)
  10. added
  11. >>> a + b
  12. Vec(4, 4, 4)
  13. subtracted
  14. >>> a - b
  15. Vec(-2, 0, 2)
  16. and multiplied by a scalar on the left
  17. >>> 3.0 * a
  18. Vec(3.0, 6.0, 9.0)
  19. or on the right
  20. >>> a * 3.0
  21. Vec(3.0, 6.0, 9.0)
  22. """
  23. def __init__(self, *v):
  24. self.v = list(v)
  25. @classmethod
  26. def fromlist(cls, v):
  27. if not isinstance(v, list):
  28. raise TypeError
  29. inst = cls()
  30. inst.v = v
  31. return inst
  32. def __repr__(self):
  33. args = ', '.join(repr(x) for x in self.v)
  34. return 'Vec({})'.format(args)
  35. def __len__(self):
  36. return len(self.v)
  37. def __getitem__(self, i):
  38. return self.v[i]
  39. def __add__(self, other):
  40. # Element-wise addition
  41. v = [x + y for x, y in zip(self.v, other.v)]
  42. return Vec.fromlist(v)
  43. def __sub__(self, other):
  44. # Element-wise subtraction
  45. v = [x - y for x, y in zip(self.v, other.v)]
  46. return Vec.fromlist(v)
  47. def __mul__(self, scalar):
  48. # Multiply by scalar
  49. v = [x * scalar for x in self.v]
  50. return Vec.fromlist(v)
  51. __rmul__ = __mul__
  52. def test():
  53. import doctest
  54. doctest.testmod()
  55. test()