symbian-qemu-0.9.1-12/python-2.6.1/Demo/classes/Vec.py
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 # A simple vector class
       
     2 
       
     3 
       
     4 def vec(*v):
       
     5     return Vec(*v)
       
     6 
       
     7 
       
     8 class 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 
       
    45 def 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 
       
    54 test()