1 | n/a | #!/usr/bin/env python3 |
---|

2 | n/a | |
---|

3 | n/a | """ |
---|

4 | n/a | A demonstration of classes and their special methods in Python. |
---|

5 | n/a | """ |
---|

6 | n/a | |
---|

7 | n/a | class Vec: |
---|

8 | n/a | """A simple vector class. |
---|

9 | n/a | |
---|

10 | n/a | Instances of the Vec class can be constructed from numbers |
---|

11 | n/a | |
---|

12 | n/a | >>> a = Vec(1, 2, 3) |
---|

13 | n/a | >>> b = Vec(3, 2, 1) |
---|

14 | n/a | |
---|

15 | n/a | added |
---|

16 | n/a | >>> a + b |
---|

17 | n/a | Vec(4, 4, 4) |
---|

18 | n/a | |
---|

19 | n/a | subtracted |
---|

20 | n/a | >>> a - b |
---|

21 | n/a | Vec(-2, 0, 2) |
---|

22 | n/a | |
---|

23 | n/a | and multiplied by a scalar on the left |
---|

24 | n/a | >>> 3.0 * a |
---|

25 | n/a | Vec(3.0, 6.0, 9.0) |
---|

26 | n/a | |
---|

27 | n/a | or on the right |
---|

28 | n/a | >>> a * 3.0 |
---|

29 | n/a | Vec(3.0, 6.0, 9.0) |
---|

30 | n/a | """ |
---|

31 | n/a | def __init__(self, *v): |
---|

32 | n/a | self.v = list(v) |
---|

33 | n/a | |
---|

34 | n/a | @classmethod |
---|

35 | n/a | def fromlist(cls, v): |
---|

36 | n/a | if not isinstance(v, list): |
---|

37 | n/a | raise TypeError |
---|

38 | n/a | inst = cls() |
---|

39 | n/a | inst.v = v |
---|

40 | n/a | return inst |
---|

41 | n/a | |
---|

42 | n/a | def __repr__(self): |
---|

43 | n/a | args = ', '.join(repr(x) for x in self.v) |
---|

44 | n/a | return 'Vec({})'.format(args) |
---|

45 | n/a | |
---|

46 | n/a | def __len__(self): |
---|

47 | n/a | return len(self.v) |
---|

48 | n/a | |
---|

49 | n/a | def __getitem__(self, i): |
---|

50 | n/a | return self.v[i] |
---|

51 | n/a | |
---|

52 | n/a | def __add__(self, other): |
---|

53 | n/a | # Element-wise addition |
---|

54 | n/a | v = [x + y for x, y in zip(self.v, other.v)] |
---|

55 | n/a | return Vec.fromlist(v) |
---|

56 | n/a | |
---|

57 | n/a | def __sub__(self, other): |
---|

58 | n/a | # Element-wise subtraction |
---|

59 | n/a | v = [x - y for x, y in zip(self.v, other.v)] |
---|

60 | n/a | return Vec.fromlist(v) |
---|

61 | n/a | |
---|

62 | n/a | def __mul__(self, scalar): |
---|

63 | n/a | # Multiply by scalar |
---|

64 | n/a | v = [x * scalar for x in self.v] |
---|

65 | n/a | return Vec.fromlist(v) |
---|

66 | n/a | |
---|

67 | n/a | __rmul__ = __mul__ |
---|

68 | n/a | |
---|

69 | n/a | |
---|

70 | n/a | def test(): |
---|

71 | n/a | import doctest |
---|

72 | n/a | doctest.testmod() |
---|

73 | n/a | |
---|

74 | n/a | test() |
---|