4
A demonstration of classes and their special methods in Python.
8
"""A simple vector class.
10
Instances of the Vec class can be constructed from numbers
23
and multiplied by a scalar on the left
31
def __init__(self, *v):
36
if not isinstance(v, list):
43
args = ', '.join(repr(x) for x in self.v)
44
return 'Vec({})'.format(args)
49
def __getitem__(self, i):
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)
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)
62
def __mul__(self, scalar):
64
v = [x * scalar for x in self.v]
65
return Vec.fromlist(v)