python捕获函数
作者:互联网
我写了下面的代码.
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.
解决方法:
实现预期效果的一种方法是:
class Vec(list):
pass
functions = {"__add__": operator.add,
"__mul__": operator.mul,
"__truediv__": operator.truediv,
"__sub__": operator.sub}
for name, op in functions.iteritems():
setattr(Vec, name, lambda self, other, op=op: Vec(map(op, self, other)))
请注意,必须使用op = op参数,以避免lambda函数成为op的闭包.
但是,使用NumPy可能会好得多–与使用纯Python创建自己的代码相比,它提供了更加通用和有效的数值数组实现.
标签:operator-keyword,python,function 来源: https://codeday.me/bug/20191201/2078587.html