概念解释
运算符重载(Operator Overloading)是Python中的一种特性,允许程序员为自定义类定义运算符的行为。通过运算符重载,我们可以使自定义类的对象支持加法、减法、比较等操作,从而使代码更加直观和简洁。
在Python中,运算符重载是通过在类中定义特殊方法(也称为魔术方法或双下划线方法)来实现的。这些特殊方法的名称以双下划线开头和结尾,例如 __add__、__sub__、__eq__ 等。
常见的运算符重载方法
以下是一些常见的运算符重载方法及其对应的运算符:
__add__(self, other):对应+运算符__sub__(self, other):对应-运算符__mul__(self, other):对应*运算符__truediv__(self, other):对应/运算符__floordiv__(self, other):对应//运算符__mod__(self, other):对应%运算符__pow__(self, other):对应**运算符__eq__(self, other):对应==运算符__ne__(self, other):对应!=运算符__lt__(self, other):对应<运算符__le__(self, other):对应<=运算符__gt__(self, other):对应>运算符__ge__(self, other):对应>=运算符
编程示例
下面通过一个具体的示例来展示如何实现运算符重载。
示例:实现一个复数类
我们定义一个 Complex 类来表示复数,并重载一些运算符,使其支持复数的加法、减法和比较操作。
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def __sub__(self, other):
return Complex(self.real - other.real, self.imag - other.imag)
def __mul__(self, other):
real = self.real * other.real - self.imag * other.imag
imag = self.real * other.imag + self.imag * other.real
return Complex(real, imag)
def __eq__(self, other):
return self.real == othe

最低0.47元/天 解锁文章
1446

被折叠的 条评论
为什么被折叠?



