__rmul__表示__mul__的反面
而__radd__表示__add__
。。。在
当左侧运算符为正常操作返回NotImplemented时调用这些函数(因此操作2 + vector_instance将首先尝试:(2).__add__(vector_instance),但如果返回{},则调用vector_instance.__radd__(2))。在
但是我不会在算术特殊方法中使用isinstance检查,这将导致大量代码重复。在
实际上,您可以在__init__中创建一个特殊情况,并在那里实现从标量到Vector的转换:class Vector(object):
def __init__(self, x, y=None, z=None):
if y is None and z is None:
if isinstance(x, Vector):
self.x, self.y, self.z = x.x, x.y, x.z
else:
self.x, self.y, self.z = x, x, x
elif y is None or z is None:
raise ValueError('Either x, y and z must be given or only x')
else:
self.x, self.y, self.z = x, y, z
def __mul__(self, other):
other = Vector(other)
return Vector(self.x*other.x, self.y*other.y, self.z*other.z)
__rmul__ = __mul__ # commutative operation
def __sub__(self, other):
other = Vector(other)
return Vector(self.x-other.x, self.y-other.y, self.z-other.z)
def __rsub__(self, other): # not commutative operation
other = Vector(other)
return other - self
def __repr__(self):
return 'Vector({self.x}, {self.y}, {self.z})'.format(self=self)
这应该如预期的那样工作:
^{pr2}$
请注意,这是一个快速而肮脏的草稿(可能有几个bug)。我只想介绍一个“总体思路”,如何在每个算术运算中不使用特殊的类型大小写来解决这个问题。在