Changeset 391 for python/trunk/Demo/classes/Vec.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Demo/classes/Vec.py
r2 r391 1 # A simple vector class 1 class Vec: 2 """ A simple vector class 2 3 4 Instances of the Vec class can be constructed from numbers 3 5 4 def vec(*v): 5 return Vec(*v)6 >>> a = Vec(1, 2, 3) 7 >>> b = Vec(3, 2, 1) 6 8 9 added 10 >>> a + b 11 Vec(4, 4, 4) 7 12 8 class Vec: 13 subtracted 14 >>> a - b 15 Vec(-2, 0, 2) 9 16 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 """ 10 25 def __init__(self, *v): 11 26 self.v = list(v) 12 27 13 def fromlist(self, v): 28 @classmethod 29 def fromlist(cls, v): 14 30 if not isinstance(v, list): 15 31 raise TypeError 16 self.v = v[:] 17 return self 32 inst = cls() 33 inst.v = v 34 return inst 18 35 19 36 def __repr__(self): 20 return 'vec(' + repr(self.v)[1:-1] + ')' 37 args = ', '.join(repr(x) for x in self.v) 38 return 'Vec({0})'.format(args) 21 39 22 40 def __len__(self): … … 28 46 def __add__(self, other): 29 47 # Element-wise addition 30 v = map(lambda x, y: x+y, self, other)31 return Vec ().fromlist(v)48 v = [x + y for x, y in zip(self.v, other.v)] 49 return Vec.fromlist(v) 32 50 33 51 def __sub__(self, other): 34 52 # Element-wise subtraction 35 v = map(lambda x, y: x-y, self, other)36 return Vec ().fromlist(v)53 v = [x - y for x, y in zip(self.v, other.v)] 54 return Vec.fromlist(v) 37 55 38 56 def __mul__(self, scalar): 39 57 # Multiply by scalar 40 v = map(lambda x: x*scalar, self.v)41 return Vec ().fromlist(v)58 v = [x * scalar for x in self.v] 59 return Vec.fromlist(v) 42 60 61 __rmul__ = __mul__ 43 62 44 63 45 64 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 65 import doctest 66 doctest.testmod() 53 67 54 68 test()
Note:
See TracChangeset
for help on using the changeset viewer.