-
Notifications
You must be signed in to change notification settings - Fork 4
/
vector6.py
executable file
·72 lines (54 loc) · 1.48 KB
/
vector6.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#! /usr/bin/python
class Vector(object):
"""
Documentation on how to use the `Vector` class.
>>> v = Vector(1, 2)
All python code executed whitin the same docstring is executed in
the same session, so that you can easily interleave python code and
explanations.
>>> print(v)
<1,2>
Vectors define two attributes, which are the `x` and `y`
coordinates:
>>> v.x
1
>>> v.y
2
You can add two vectors
>>> v2 = Vector(2,3)
>>> print(v + v2)
<3,5>
Multiply a vector for a scalar (the next test will fail)
>>> print(v * 2)
<2,1>
please note that multiplication is NOT commutative:
>>> print(2 * v)
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for *: 'int' and 'Vector'
and of course you can check if two vectors are the same
>>> Vector(1, 2) == Vector(1, 2)
True
>>> Vector(1, 2) == Vector(4, 5)
false
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __mul__(self, scalar):
"""
Any docstring from any method will be searched for tests.
>>> v = Vector(1, 2)
>>> print(v * 2)
<2,4>
"""
return Vector(scalar*self.x, scalar*self.y)
def __str__(self):
return ("<%g,%g>" % (self.x, self.y))
def __eq__(self, other):
return (self.x == other.x) and (self.y == other.y)
def __add__(self, other):
return Vector(self.x+other.x, self.y+other.y)
if __name__ == '__main__':
import doctest
doctest.testmod()