PageRenderTime 584ms CodeModel.GetById 372ms app.highlight 5ms RepoModel.GetById 108ms app.codeStats 1ms

/Demo/classes/Vec.py

http://unladen-swallow.googlecode.com/
Python | 54 lines | 34 code | 16 blank | 4 comment | 2 complexity | f33cd1a110e8ab25e4cb14b955f39f93 MD5 | raw file
 1# A simple vector class
 2
 3
 4def vec(*v):
 5    return Vec(*v)
 6
 7
 8class Vec:
 9
10    def __init__(self, *v):
11        self.v = list(v)
12
13    def fromlist(self, v):
14        if not isinstance(v, list):
15            raise TypeError
16        self.v = v[:]
17        return self
18
19    def __repr__(self):
20        return 'vec(' + repr(self.v)[1:-1] + ')'
21
22    def __len__(self):
23        return len(self.v)
24
25    def __getitem__(self, i):
26        return self.v[i]
27
28    def __add__(self, other):
29        # Element-wise addition
30        v = map(lambda x, y: x+y, self, other)
31        return Vec().fromlist(v)
32
33    def __sub__(self, other):
34        # Element-wise subtraction
35        v = map(lambda x, y: x-y, self, other)
36        return Vec().fromlist(v)
37
38    def __mul__(self, scalar):
39        # Multiply by scalar
40        v = map(lambda x: x*scalar, self.v)
41        return Vec().fromlist(v)
42
43
44
45def test():
46    a = vec(1, 2, 3)
47    b = vec(3, 2, 1)
48    print a
49    print b
50    print a+b
51    print a-b
52    print a*3.0
53
54test()