我可以在类声明中使用重载运算符吗?

我试图在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()
aidetianshi123456 回答:我可以在类声明中使用重载运算符吗?

在Python 3中, 1 对于__truediv__使用/,对于(__floordiv__)使用//

这在带有from __future__ import division的Python 2中也起作用(这使得除法行为与Python 3中的一样)。


以下是另外两个建议:

首先,您可以使用numbers模块中的类来检查数字类型,而不是检查确切的类型floatint

第二,如果它不知道如何处理给定值,则应从覆盖的二进制运算符返回NotImplemented。然后,Python将检查另一个操作数是否实现了操作符的翻转版本(即__r[name]__),然后尝试进行操作。如果它还返回NotImplemented,Python将引发TypeError。这样,您就可以创建可在运算符的两侧使用的类。

import numbers

class Vector1D:
  def __init__(self,x):
    self.x = x
  def __repr__(self,x):
    return "Vector1D({})".format(self.x)

  def __mul__(self,other):
    if isinstance(other,numbers.Number):
      return self.__class__(self.x * other)
    return NotImplemented

  def __rmul__(self,other):
    # x * vec1d == vec1d * x
    return self.__mul__(other)

  def __rtruediv__(self,other):
    # You can't divide things by a Vector1D
    return NotImplemented

vec2 = Vector1D(2)

vec2 * 3
# Runs vec2.__mul__(2),gets Vector1D(6)

3 * vec2
# First tries int.__mul__(3,vec2),gets NotImplemented
# Then tries Vector1D.__rmul__(vec2,3),gets Vector1D(6)

3 / vec2
# First tries int.__truediv__(3,gets NotImplemented
# Then tries Vector1D.__rtruediv__(vec2,gets NotImplemented
# Python raises TypeError
本文链接:https://www.f2er.com/3131056.html

大家都在问