Python-运算符重载(Operator Overloading)

概念解释

运算符重载(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要重新演唱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值