【发布时间】:2019-11-09 22:29:53
【问题描述】:
我正在尝试在 python 中创建一个简单的 Vector 类,但我意识到我不能在像 c++ 这样的方法中使用以前重载的运算符。我有什么错误吗?或者它是如何工作的?
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'
【问题讨论】:
-
__div__在 Python 3 中不是一个东西。__truediv__对应于/,__floordiv__对应于//。 -
@user2357112 谢谢我不知道:D
-
这里有一些其他提示:被覆盖的数学运算符如果不知道该做什么应该
return NotImplemented(然后Python 将检查其他操作数是否支持适当的操作)。而不是检查type(other) ==,您可以使用isinstance和numbers模块中的抽象基数类:isinstance(other, numbers.Number)。 -
@jirassimok 操作实现;
TypeError会更合适,就像float.__rdiv__现在正在加注一样。 -
@chepner
float的操作员不会引发TypeError,他们会返回NotImplemented(尝试(1.0).__truediv__(None))。如果两个操作数都返回NotImplemented,Python 会自动生成TypeError。如果您在__truediv__中手动提出TypeError,您会阻止其他类能够划分您的类,即使它们实现了__rtruediv__。
标签: python class operator-overloading