Python算术/反向算术/比较/复合赋值算术/位/一元/,in / not in/索引和切片运算符重载(重写)、slice 构造函数重写

Python算术/反向算术/比较/复合赋值算术/位/一元/,in / not in/索引和切片运算符重载(重写)、slice 构造函数重写

运算符重载

什么是运算符重载:让自定义的类生成的对象(实例)能够使用运算符进行操作

作用:

让自定义的类的实例像内建对象一样运行运算符操作

让程序简洁易读

对自定义的对象,将运算符赋予新的运算规则

算术运算符的重载

__add__(self, rhs) self + rhs 加法

__sub__(self, rhs) self - rhs 减法

__mul__(self, rhs) self * rhs 乘法

__truediv__(self, rhs) self / rhs 除法

__floordiv__(self, rhs) self // rhs 地板除法

__mod__(self, rhs) self % rhs 求余

__pow__(self, rhs) self ** rhs

注:rhs (right hands side) 右手边

反向算术运算符的重载

当左手边的类型为内建类型,右手边为自定义类型时,要实现运算必须用以下方法重载

反向算术运算符的重载

__radd__(self, lhs) lhs +  self 加法

__rsub__(self, lhs) lhs -  self 减法

__rmul__(self, lhs) lhs *  self 乘法

__rtruediv__(self, lhs) lhs /  self 除法

__rfloordiv__(self, lhs) lhs // self 地板除法

__rmod__(self, lhs) lhs %  self 求余

__rpow__(self, lhs) lhs ** self

复合赋值算术运算符的重载

__iadd__(self, rhs) self += rhs 加法

__isub__(self, rhs) self -= rhs 减法

__imul__(self, rhs) self *= rhs 乘法

__itruediv__(self, rhs) self /= rhs 除法

__ifloordiv__(self, rhs) self //= rhs 地板除法

__imod__(self, rhs) self %= rhs 求余

__ipow__(self, rhs) self **= rhs

比较运算符的重载

__lt__(self, rhs) self <  rhs 小于

__le__(self, rhs) self <= rhs 小于等于

__gt__(self, rhs) self >  rhs 大于

__ge__(self, rhs) self >= rhs 大于等于

__eq__(self, rhs) self == rhs 等于

__ne__(self, rhs) self != rhs 不等于

注:比较运算符通常返回 True 或False

位运算符重载

__invert__(self) ~ self 取反(一元运算符)

__and__(self, rhs) self &  rhs 位与

__or__(self, rhs) self |  rhs 位或

__xor__(self, rhs) self ^  rhs 位异或

__lshift__(self, rhs) self << rhs 左移

__rshift__(self, rhs) self >> rhs 右移

反向位运算符重载

__rand__(self, lhs) lhs &  self    位与

__ror__(self, lhs) lhs |  self    位或

__rxor__(self, lhs) lhs ^  self    位异或

__rlshift__(self, lhs) lhs << self    左移

__rrshift__(self, lhs) lhs >> self    右移

复合赋值位运算符重载

__iand__(self, rhs) self &=  rhs 位与

__ior__(self, rhs) self |=  rhs 位或

__ixor__(self, rhs) self ^=  rhs 位异或

__ilshift__(self, rhs) self <<= rhs 左移

__irshift__(self, rhs) self >>= rhs 右移

一元运算符的重载

__neg__(self) - self 负号

__pos__(self) + self 正号

__invert__(self) ~ self 取反

运算符重载说明:运算符重载不能改变运算符的优先级

in / not in 运算符的重载

重载方法:

__contains__(self, e) e in self  成员运算

索引和切片运算符的重载

__getitem__(self, i) x = self[i] 索引/切片取值

__setitem__(self, i, v) self[i] =v 索引/切片赋值

__delitem__(self, i) del self[i] del语句删除索引等

作用:让自定义的类型的对象能够支持索引和切片操作

slice 构造函数

作用:

用于创建一个slice切片对象,此对象存储一个切片的起始值,终止值和步长信息

slice(start, stop=None, step=None) 创建一个切片对象

slice的对象的属性:

s.start 切片起始值,默认为None

s.stop 切片终止值,默认为None

s.step 切片步长,默认为None


最后编辑于:2020/09/30作者: 牛逼PHP

发表评论