【发布时间】:2019-12-09 14:55:21
【问题描述】:
考虑以下在 Python 中具有所有向量操作的向量对象的实现:
import operator
class Vector:
def __init__(self, value):
self._vals = value.copy()
@classmethod
def _op(cls, this, that, oper, rev=False):
assert isinstance(this, cls)
if rev:
op = lambda a, b : oper(b, a)
else:
op = oper
if isinstance(that, list):
result = [op(x, y) for (x, y) in zip(this._vals, that)]
elif isinstance(that, cls):
result = [op(x, y) for (x, y) in zip(this._vals, that._vals)]
else:
# assume other is scalar
result = [op(x, that) for x in this._vals]
return cls(result)
def __add__(self, other):
return Vector._op(self, other, operator.add, False)
def __radd__(self, other):
return Vector._op(self, other, operator.add, True)
def __sub__(self, other):
return Vector._op(self, other, operator.sub, False)
def __rsub__(self, other):
return Vector._op(self, other, operator.sub, True)
def __mul__(self, other):
return Vector._op(self, other, operator.mul, False)
def __rmul__(self, other):
return Vector._op(self, other, operator.mul, True)
def __truediv__(self, other):
return Vector._op(self, other, operator.truediv, False)
def __rtruediv__(self, other):
return Vector._op(self, other, operator.truediv, True)
def __str__(self):
return str(self._vals)
很明显,所有重载的运算符(__add__、__radd__、...)都有完全相同的代码,除了传递给私有类方法 @ 的 oper 和 rev 参数987654327@。
有没有办法避免所有的复制粘贴和自动(或半自动)这些操作?
【问题讨论】:
-
R 版本仅在没有正常版本可用时使用。查看stackoverflow.com/questions/9126766/…中的答案
标签: python operator-overloading