source: python/trunk/Demo/classes/Vec.py

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 1.3 KB
RevLine 
[391]1class Vec:
2 """ A simple vector class
[2]3
[391]4 Instances of the Vec class can be constructed from numbers
[2]5
[391]6 >>> a = Vec(1, 2, 3)
7 >>> b = Vec(3, 2, 1)
[2]8
[391]9 added
10 >>> a + b
11 Vec(4, 4, 4)
[2]12
[391]13 subtracted
14 >>> a - b
15 Vec(-2, 0, 2)
[2]16
[391]17 and multiplied by a scalar on the left
18 >>> 3.0 * a
19 Vec(3.0, 6.0, 9.0)
20
21 or on the right
22 >>> a * 3.0
23 Vec(3.0, 6.0, 9.0)
24 """
[2]25 def __init__(self, *v):
26 self.v = list(v)
27
[391]28 @classmethod
29 def fromlist(cls, v):
[2]30 if not isinstance(v, list):
31 raise TypeError
[391]32 inst = cls()
33 inst.v = v
34 return inst
[2]35
36 def __repr__(self):
[391]37 args = ', '.join(repr(x) for x in self.v)
38 return 'Vec({0})'.format(args)
[2]39
40 def __len__(self):
41 return len(self.v)
42
43 def __getitem__(self, i):
44 return self.v[i]
45
46 def __add__(self, other):
47 # Element-wise addition
[391]48 v = [x + y for x, y in zip(self.v, other.v)]
49 return Vec.fromlist(v)
[2]50
51 def __sub__(self, other):
52 # Element-wise subtraction
[391]53 v = [x - y for x, y in zip(self.v, other.v)]
54 return Vec.fromlist(v)
[2]55
56 def __mul__(self, scalar):
57 # Multiply by scalar
[391]58 v = [x * scalar for x in self.v]
59 return Vec.fromlist(v)
[2]60
[391]61 __rmul__ = __mul__
[2]62
63
64def test():
[391]65 import doctest
66 doctest.testmod()
[2]67
68test()
Note: See TracBrowser for help on using the repository browser.