【发布时间】:2018-07-14 23:30:59
【问题描述】:
我有一个 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 是一个向量,我可以乘以一个浮点数。 在我的代码的许多部分中,向量乘以浮点数而没有错误。
有谁知道这种不一致来自哪里?
谢谢
【问题讨论】:
-
你确定你是
Vector2() * 1.0而不是1.0 * Vector2()? -
哇,原来如此。为什么这很重要?
-
因为
float * whatever是由float定义的,而whatever * float是由whatever定义的 -
有道理,感谢您的快速响应!
标签: python overloading operator-keyword