我有一个Vector2类:
class Vector2():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector2(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Vector2(self.x * other, self.y * other)
def __neg__(self):
return Vector2(-self.x, -self.y)
def magnitude(self):
return math.sqrt(self.x ** 2 + self.y ** 2)
@classmethod
def distance(self, v1, v2):
return math.sqrt((v2.x - v1.x) ** 2 + (v2.y - v1.y) ** 2)
def normalize(self):
return self * (1/self.magnitude())
当我尝试执行1.0 * Vector2()
时,收到错误: TypeError:不支持*的操作数类型:'float‘和'instance’
然而,有时它会按预期工作:
#this works as intended, s is a float
ball.pos -= ball.vel.normalize() * s
ball.vel是一个向量,我可以乘以一个浮点数。在我的代码的许多部分中,向量乘以浮点数都没有错误。
有人知道这种不一致是从哪里来的吗?
谢谢
发布于 2018-07-15 07:39:35
定义一个让a_float * a_vector
正常工作的__rmul__
方法。它可以像这样简单
def __rmul__(self, other):
return self * other
其他运营商也有a dunder-r
version。当没有为给定类型定义普通版本时,将调用这些反射运算符。有关NotImplemented
内置常量的信息,请参阅文档。
表达式a * b
等同于a.__mul__(b)
,除非b
是a
类的子类的实例,或者a.__mul__(b)
返回NotImplemented
,在这种情况下返回的是b.__rmul__(a)
。
https://stackoverflow.com/questions/51344164
复制相似问题