python笔记(十七)运算符重载

一.加减乘除

__add__(self,other)
__sub__(self,other)
__mul__(self,other)
真除__truediv__(self,other)
地板除__floordiv__(self,other)

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def __add__(self,other):
        self.x = self.x + other.x
        self.y = self.y + other.y

在这里插入图片描述

二.反运算符

例如加__radd__(self,other)
如果出现 3 - b 这样的算式,程序就开始调用 bradd函数

class Nint(int):
    def __rsub__(self,other):
        return int.__sub__(other,self)    

3 - b中3不是对象,所以开始调用b的反运算
这个代码中我们return int.__sub__(other,self)otherself换了个位置
所以才是 3 - 5
在这里插入图片描述
other 就是 3
self 就是 5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值