1#!/usr/bin/env python3 2 3""" 4A demonstration of classes and their special methods in Python. 5""" 6 7class Vec: 8 """A simple vector class. 9 10 Instances of the Vec class can be constructed from numbers 11 12 >>> a = Vec(1, 2, 3) 13 >>> b = Vec(3, 2, 1) 14 15 added 16 >>> a + b 17 Vec(4, 4, 4) 18 19 subtracted 20 >>> a - b 21 Vec(-2, 0, 2) 22 23 and multiplied by a scalar on the left 24 >>> 3.0 * a 25 Vec(3.0, 6.0, 9.0) 26 27 or on the right 28 >>> a * 3.0 29 Vec(3.0, 6.0, 9.0) 30 """ 31 def __init__(self, *v): 32 self.v = list(v) 33 34 @classmethod 35 def fromlist(cls, v): 36 if not isinstance(v, list): 37 raise TypeError 38 inst = cls() 39 inst.v = v 40 return inst 41 42 def __repr__(self): 43 args = ', '.join(repr(x) for x in self.v) 44 return 'Vec({})'.format(args) 45 46 def __len__(self): 47 return len(self.v) 48 49 def __getitem__(self, i): 50 return self.v[i] 51 52 def __add__(self, other): 53 # Element-wise addition 54 v = [x + y for x, y in zip(self.v, other.v)] 55 return Vec.fromlist(v) 56 57 def __sub__(self, other): 58 # Element-wise subtraction 59 v = [x - y for x, y in zip(self.v, other.v)] 60 return Vec.fromlist(v) 61 62 def __mul__(self, scalar): 63 # Multiply by scalar 64 v = [x * scalar for x in self.v] 65 return Vec.fromlist(v) 66 67 __rmul__ = __mul__ 68 69 70def test(): 71 import doctest 72 doctest.testmod() 73 74test() 75