ยปCore Development>Code coverage>Tools/demo/vector.py

Python code coverage for Tools/demo/vector.py

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