【发布时间】:2012-07-01 04:05:15
【问题描述】:
我有一个向量类,我定义了__mul__ 方法来将向量乘以一个数字。
这是__mul__ 方法:
def __mul__(self, other):
x = self.x * other
y = self.y * other
new = Vector()
new.set_pos((x, y))
return new
我的问题是我不知道数字和向量之间哪个是哪个。 如果 self 是数字,self.x 会引发错误。 (我可能在这一点上弄错了:“其他”总是一个数字吗?)
所以我在这里找到了:Python: multiplication override 我能做到的:
__rmul__ = __mul__
但是如何在类定义中做到这一点?
类似:
def __rmul__ = __mul__
【问题讨论】:
标签: python class operator-overloading overriding operator-keyword