我试图在python中创建一个简单的Vector类,但我意识到我不能在像c ++这样的方法中使用以前重载的运算符。我有什么错误吗?或其python如何工作?
class Vector3D:
#constructor
def __init__(self,x,y,z):
self.x = x
self.y = y
self.z = z
#overloading division operator for just numbers
def __div__(self,other):
if type(other) == int or type(other) == float:
return Vector3D(self.x/other,self.y/other,self.z/other)
print("Error")
return
#Used in the normalize method
def Magnitude(self):
return math.sqrt(self.x**2+ self.y**2 + self.z**2)
# ==> using the division operator in normalization
def Normalize(self):
return self / self.Magnitude()
# <== Throws: TypeError: unsupported operand type(s) for /: 'Vector3D' and 'float'
已解决(感谢@ user2357112和@jirassimok):
class Vector3D:
#constructor
def __init__(self,z):
self.x = x
self.y = y
self.z = z
def __truediv__(self,other):
if isinstance(other,numbers.Number):
return Vector3D(self.x/other,self.z/other)
print("Error")
return
def Magnitude(self):
return math.sqrt(self.x**2+ self.y**2 + self.z**2)
# ==> using the division operator in normalization
def Normalize(self):
return self / self.Magnitude()