我编写了以下有效的代码。
from operator import mul
from operator import truediv #python 3.2
class Vec(list):
def __mul__(self, other):
return Vec(map(mul, self, other))
def __truediv__(self, other):
return Vec(map(truediv, self, other))
>>> xs = Vec([1,2,3,4,5])
>>> ys = Vec([4,5,6,7,4])
>>> zs = xs * ys
>>> zs.__class__
<class 'vector.Vec'>
>>> zs
[4, 10, 18, 28, 20]
但是否有可能创建这样的东西:
class Vec(list):
allowed_math = [__add__, __mul__, __truediv__, __subtract__] # etc
def __catchfunction__(self, other, function):
if function in allowed_math:
return Vec(map(function, self, other))
澄清一下,这不是我试图重新创建 NumPy,我只是想了解如何使用 Python。