Los métodos especiales (no todos) son los siguientes:
In [16]:
a = [1, 2, 3]
print(a + [4, 5, 6])
print(a * 2)
Crearemos una clase Vector (como una especialización de list) para que estar operaciones se comporten como lo harían en un vector.
In [1]:
import itertools
class NotMatchingShapes(Exception):
pass
class Vector(list):
def __add__(self, other):
if len(self) != len(other):
raise NotMatchingShapes
return Vector([x+y for x,y in zip(self, other)])
v1 = Vector([1, 2, 3])
v1 + [4, 5, 6]
Out[1]:
In [14]:
class Vector(list):
def __add__(self, other):
if len(self) != len(other):
raise NotMatchingShapes
return Vector([x+y for x,y in zip(self, other)])
def __mul__(self, other):
if isinstance(other, Vector):
return Vector([x*y for x,y in zip(self, other)])
return Vector([x*other for x in self])
def __repr__(self):
return "Vector({})".format(list.__repr__(self))
v1 = Vector([1, 2, 3])
print(v1 * 3)
print(v1 * Vector([4, 5 ,6]))