所谓 重载运算符(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重载运算符使用方式
下面是一个简单的例子,展示了如何给类重载一个加法运算符:
Python技术站热门推荐:
PDF电子发票识别软件,一键识别电子发票并导入到Excel中!
10大顶级数据挖掘软件!
人工智能的十大作用!
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 对象即可。
需要注意的是,重载运算符应该符合其原本的含义,以免造成混淆。此外,对于不支持重载的运算符,可以通过定义相应的特殊方法来实现类似的效果。
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did254566