Python---运算符重载

本文详细介绍了Python中的运算符重载,包括算数、反向算数、复合赋值算术、比较和位运算符的重载方法及用途,帮助理解如何自定义类实现对象间的各种运算操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是运算符重载:

让自定义的类生成的对象(实例)能够使用运算符进行操作.

算数运算符重载:

方法名                             运算符和表达式            说明
            __add__(self,other)        self + other                   加法
            __sub__(self,other)        self - other                    减法
            __mul__(self,other)        self * other                    乘法
            __truediv__(self,other)   self / other                    除法
            __floordiv__(self,other)  self // other                   地板除
            __mod__(self,other)       self % other                 取模(求余)
            __pow__(self,other)       self **other                   幂运算

class Person:
    def __init__(self,num):
        self.num = num
    def __add__(self, other):
        return Person(self.num + other.num)
    def __sub__(self, other):
        return Person(self.num - other.num)
    def __str__(self):
        return "num = "+str(self.num)

p1 = Person(12)
p2 = Person(13)
print(p1+p2)
print(p1-p2)



F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/运算符重载2.py
num = 25
num = -1

Process finished with exit code 0

反向算数运算符重载:

            方法名                              运算符和表达式       说明
            __radd__(self,other)        other + self               加法
            __rsub__(self,other)        other - self                减法
            __rmul__(self,other)        other * self                乘法
            __rtruediv__(self,other)   other / self                除法
            __rfloordiv__(self,other)  other // self               地板除
            __rmod__(self,other)       other % self             取模(求余)
            __rpow__(self,other)       other ** self              幂运算

class Person:
    def __init__(self,num):
        self.num = num
    def __repr__(self):
        return "num = " + repr(self.num)
    def __add__(self, other):
        print("__add__")
        return Person(self.num + other)
    def __radd__(self, other):
        print("__radd__")
        return Person(self.num + other)
    def __sub__(self, other):
        print("__sub__")
        return Person(self.num - other)
    def __rsub__(self, other):
        print("__rsub__")
        return Person(self.num - other)



p1 = Person(10)
p2 = Person(20)
p3 = 20 - p1
print(p3)
p4 = p1 - 20
print(p4)
p5 = 10 + p2
print(p5)
p6 = p2 + 10
print(p6)




F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/反向运算符重载.py
__rsub__
num = -10
__sub__
num = -10
__radd__
num = 30
__add__
num = 30

Process finished with exit code 0

 复合赋值算术运算符的重载:
        方法名                             运算符和表达式      说明
        __iadd__(self,other)        self += other           加法
        __isub__(self,other)        self -= other            减法
        __imul__(self,other)        self *= other            乘法
        __itruediv__(self,other)   self /= other            除法
        __ifloordiv__(self,other)  self //=other            地板除
        __imod__(self,other)       self %= other         取模(求余)
        __ipow__(self,other)       self **=other           幂运算

class Person:
    def __init__(self,num):
        self.num = num
    def __repr__(self):
        return "num = "+ repr(self.num)
    def __iadd__(self, other):
        print("__iadd__")
        self.num += other.num
        return self
    def __add__(self, other):
        print("__add__")
        return Person(self.num + other)

if __name__ == '__main__':
    p1 = Person(10)
    p2 = Person(20)
    p3 = p1 + 10
    print(p3)
    p2 += p1
    print(p2)



F:\学习代码\Python代码\venv\Scripts\python.exe F:/学习代码/Python代码/day5/复合算数运算符重载.py
__add__
num = 20
__iadd__
num = 30

Process finished with exit code 0

比较算数运算符:

方法名                     运算符和表达式         说明
__lt__(self, other)            self < other                             小于
__le__(self, other)           self <= other                           小于等于
__gt__(self, other)           self > other           大于
__ge__(self, other)          self >= other           大于等于
__eq__(self, other)          self == other           等于
__ne__(self, other)          self != other            不等于

 

位运算符重载
方法名                        运算符和表达式                          说明
__invert__(self)                     ~ self                                           取反(一元运算符)
__and__(self, other)             self & other                                 位与
__or__(self, other)                self | other                                   位或
__xor__(self, other)              self ^ other                                  位异或
__lshift__(self, other)            self << other                                左移
__rshift__(self, other)           self >> other                                右移

反向位运算符重载
方法名                        运算符和表达式        说明
__rand__(self, other)                           other& self             位与
__ror__(self, other)                              other| self               位或
__rxor__(self, other)                            other^ self                 位异或
__rlshift__(self, other)                          other<< self            左移
__rrshift__(self, other)                         other>> self            右移

复合赋值位运算符重载
方法名                       运算符和表达式        说明
__iand__(self, other)                self &= other             位与
__ior__(self, other)                   self |= other              位或
__ixor__(self, other)                 self ^= other                             位异或
__ilshift__(self, other)              self <<= other                          左移
__irshift__(self, other)                self >>= other          右移

 

 

 

### C++ 运算符重载实现方法 在 C++ 中,运算符重载是一种通过定义特殊函数(称为运算符重载函数)来改变标准运算符行为的机制。这些函数可以是成员函数或非成员函数[^2]。以下是一个简单的示例,展示如何重载 `+` 运算符以实现两个自定义类对象的加法操作。 ```cpp #include <iostream> using namespace std; class Complex { private: double real; double imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 重载 + 运算符 Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } void display() const { cout << real << " + " << imag << "i" << endl; } }; int main() { Complex c1(3.5, 4.2), c2(2.1, 3.7); Complex c3 = c1 + c2; // 调用重载的 + 运算符 c3.display(); // 输出结果为 5.6 + 7.9i return 0; } ``` #### Python 运算符重载使用示例 Python 中的运算符重载可以通过定义特定的魔术方法(如 `__add__`, `__sub__` 等)来实现。以下是一个示例,展示了如何重载 `+` 和 `-` 运算符以支持两个自定义类对象的操作[^1]。 ```python class Vector: def __init__(self, x=0, y=0): self.x = x self.y = y # 重载 + 运算符 def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) # 重载 - 运算符 def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __str__(self): return f"({self.x}, {self.y})" # 测试代码 v1 = Vector(3, 4) v2 = Vector(1, 2) v3 = v1 + v2 # 调用 __add__ v4 = v1 - v2 # 调用 __sub__ print(v3) # 输出: (4, 6) print(v4) # 输出: (2, 2) ``` ### 相关技术点总结 - 在 C++ 中,前置和后置运算符可以通过区分参数列表的方式实现。例如,`operator++()` 表示前置递增,而 `operator++(int)` 表示后置递增[^2]。 -Python 中,运算符重载更加简洁,通常只需要实现对应的魔术方法即可完成复杂的功能[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值