VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python重载运算符详解

所谓重载运算符(operator overloading),指的是在类中定义并实现一个与运算符对应的处理方法,这样当类对象在进行运算符操作时,系统就会调用类中相应的方法来处理。

也就是说,可以通过重载运算符来改变内置对象的行为,使得这些对象可以支持自定义的运算符操作,比如对类对象的+、-、×、÷等。

Python 中可以重载的运算符有很多,下面列举了一些常用的运算符及其对应的方法:

Python重载运算符

算术运算符:+、-、*、/、//、%、**

  • add(self, other):定义 + 运算符的行为
  • sub(self, other):定义 - 运算符的行为
  • mul(self, other):定义 * 运算符的行为
  • truediv(self, other):定义 / 运算符的行为
  • floordiv(self, other):定义 // 运算符的行为
  • mod(self, other):定义 % 运算符的行为
  • pow(self, other):定义 ** 运算符的行为

位运算符:&、|、^、~、<<、>>

  • and(self, other):定义 & 运算符的行为
  • or(self, other):定义 | 运算符的行为
  • xor(self, other):定义 ^ 运算符的行为
  • invert(self):定义 ~ 运算符的行为
  • lshift(self, other):定义 << 运算符的行为
  • rshift(self, other):定义 >> 运算符的行为

比较运算符:<、<=、>、>=、==、!=

  • lt(self, other):定义 < 运算符的行为
  • le(self, other):定义 <= 运算符的行为
  • gt(self, other):定义 > 运算符的行为
  • ge(self, other):定义 >= 运算符的行为
  • eq(self, other):定义 == 运算符的行为
  • ne(self, other):定义 != 运算符的行为

逻辑运算符:and、or、not

  • and(self, other):定义 and 运算符的行为
  • or(self, other):定义 or 运算符的行为
  • not(self):定义 not 运算符的行为

赋值运算符:=

  • eq(self, other):定义 = 运算符的行为

Python重载运算符使用方式

下面是一个简单的例子,展示了如何给类重载一个加法运算符:

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __str__(self):
        return "({}, {})".format(self.x, self.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)  # 输出 (4, 6)

在这个例子中,我们定义了一个名为 Vector 的类,该类包含 x 和 y 两个属性,以及重载的 add 方法。

当对两个 Vector 对象进行加法运算时,会调用 add 方法,返回一个新的 Vector 对象,其中 x 和 y 分别为两个 Vector 对象对应属性之和。最后,使用 print 函数输出新的 Vector 对象即可。

需要注意的是,重载运算符应该符合其原本的含义,以免造成混淆。此外,对于不支持重载的运算符,可以通过定义相应的特殊方法来实现类似的效果。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:https://pythonjishu.com/python-operator-overloading/

 

相关教程