Python基础-DAY18

重载:

  什么是重载:

    用自定义的规则实现实例方法之间的运算符操作或函数操作

 

作用:

  让实例像数学表达式一样进行运算操作

  让程序简结易读

 

重载:

  1) 函数重载

  2) 运算符重载

 

函数重载:

  让实例像内建对象一样进行内建函数操作

 

对象转字符串函数重载

repr() 函数

str() 函数

对象转字符串函数的重载方法:

  repr() 的重载方法:

    def __repr__(self):

         ...

  str() 的重载方法:

    def __str__(self):

        ...

    注: 如果没有__str__(self)方法,则返回repr(obj)函数结果代替

 

运算符重载:

作用:

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

 

算术运算符:

  __add__   加法 +

  __sub__   减法 -

  __mul__   乘法 *

  __truediv__  除法 /

  __floordiv__  地板除 //

  __mod__  取模(求余)  %

  __pow__  幂 **

 

二元运算符的重载方法格式:

    def __xxx__(self, other):

        ...

    注:二元运算符的重载方法参数列表中只能有两个参数

 

反向算术运算符重载:

  __radd__(self, lhs)   加法 lhs + self

  __rsub__(self, lhs)   减法 lhs - self

  __rmul__(self, lhs)   乘法 lhs * self

  __rtruediv__(self, lhs)   ...

  __rfloordiv__(self, lhs)   ...

  __rmod__(self, lhs)   ...

  __rpow__(self, lhs)   ...

  注: lhs(left hand side)  左手边

 

二元运算符

and or <<  >>  ^  |  & 

>  <  >=   <= == !=

 

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

__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

注:当重载后优先使用重载的方法,否则使用__add__等方法代替

 

比较运算符重载(二元运算符):

  __lt__    小于 <

  __le__    小于等于 <=

  __gt__    大于 >

  __ge__    大于等于 >=

  __eq__    等于 ==

  __ne__    不等于 !=

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

 

位操作运算符重载:

  __and__   位与 &

  __or__    位或 |

  __xor__    位异或  ^

  __lshift__  左移  <<

  __rshift__  右移  >>

 

反向位操作运算符

  __rand__

  __ror__

  ...

复合赋值位运算符重载

  __iand__

  __ior__

  ...

一元运算符的重载:

  __neg__   负号 -

  __pos__   正号 +

  __invert__  取反 ~

重载格式:

  def __xxx__(self):

      .....

 

猜你喜欢

转载自blog.csdn.net/qq_41797451/article/details/81542945