Use py_resource module
[python/dscho.git] / Demo / classes / Vec.py
blob8289bc847e0d5c19a046f915442460c53e647b95
1 # A simple vector class
4 def vec(*v):
5 return apply(Vec, v)
8 class Vec:
10 def __init__(self, *v):
11 self.v = []
12 for x in v:
13 self.v.append(x)
16 def fromlist(self, v):
17 self.v = []
18 if type(v) <> type([]):
19 raise TypeError
20 self.v = v[:]
21 return self
24 def __repr__(self):
25 return 'vec(' + `self.v`[1:-1] + ')'
27 def __len__(self):
28 return len(self.v)
30 def __getitem__(self, i):
31 return self.v[i]
33 def __add__(a, b):
34 # Element-wise addition
35 v = []
36 for i in range(len(a)):
37 v.append(a[i] + b[i])
38 return Vec().fromlist(v)
40 def __sub__(a, b):
41 # Element-wise subtraction
42 v = []
43 for i in range(len(a)):
44 v.append(a[i] - b[i])
45 return Vec().fromlist(v)
47 def __mul__(self, scalar):
48 # Multiply by scalar
49 v = []
50 for i in range(len(self.v)):
51 v.append(self.v[i]*scalar)
52 return Vec().fromlist(v)
56 def test():
57 a = vec(1, 2, 3)
58 b = vec(3, 2, 1)
59 print a
60 print b
61 print a+b
62 print a*3.0
64 test()