Python中类方法重载

Method Overloads Call for
init 构造函数 X=Class()
del 析构函数 对象销毁
repr 打印转换 print X,repr(X)
str 打印转换 print X,str(X)
call 调用函数 X()
getattr 限制 X.undefine
setattr 取值 X.any=value
getitem 索引 X[key],For If
setitem 索引 X[key]=value
contains in a in X
len 长度 len(X)
iter 迭代 For In
add + X+Y,X+=Y
sub - X-Y,X-=Y
mul XY
radd 右加+ +X
iadd += X+=Y
or | X|Y, X|=Y
cmp 比较 == X==Y,X
lt 小于< X
eq 等于= X=Y

重载方法格式:
def __xxx__(self,other):

注:重载方法格式
-----------------------------------------------------------------运算符
运算符重载:
作用:
让自定义的类创建的对象像内建对象一样进项运算符操作
算数运算符:
__add__ 加法 +
__sub__ 减法 -
__mul__ 乘法 *
__truedif__ 除法 /
__floordiv__ 地板除 //
__mod__ 取模(求余) %
__pow__ 幂 **

反向算数运算符重载:
__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
注:lhs(left hand side) 左手边

复合赋值算数运算符的重载:
__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 不等于 !=
-----------------------------------------------------------------位操作运算符
位操作运算符重载:
and 位与 &
or 位或 |
xor 位异或 ^
lshift 左移 <<
rshift 右移 >>

反向位操作运算符:
rand 位与 &
ror 位或 |
rxor 位异或 ^
rlshift 左移 <<
rrshift 右移 >>

复合赋值位运算符重载:
iand 位与 &
ior 位或 |
ixor 位异或 ^
ilshift 左移 <<
irshift 右移 >>
-----------------------------------------------------------------一元运算符
一元运算符的重载:
neg 符号 -
pos 正号 +
invert 取反 ~
重载格式:
def xxx(self):
pass
-----------------------------------------------------------------内建函数
内建函数重载:
def abs(self) abs(obj) 函数调用
def len(self) len(obj) 函数调用
def reversed(self) reversed(obj) 函数调用
def round(self) round(obj) 函数调用
-----------------------------------------------------------------数值转换函数
数值转换函数重载:
int int(obj)
float float(obj)
complex complex(obj)
bool bool(obj)
-----------------------------------------------------------------布尔测试运算符
布尔测试运算符重载:
格式:
def bool(self):

作用:

  1. 用于bool(obj) 函数取值
  2. 用于if语句真值表达式中
  3. 用于while语句真值表达式中

重载说明:
当没有 bool(self) 方法时,真值测试将取
len(self) 方法的返回值来测试布尔值
-----------------------------------------------------------------in / not in
in / not in 运算符重载:
格式:
def contains(self, e):

作用:
成员资格测试(通常)
-----------------------------------------------------------------索引和切片
索引和切片运算符的重载:
重载方法:
getitem(self, i) 方法
sefitem(self, i, v) 方法
delitem(self, i) 方法
作用:
让自定义类型的对象能进行索引和切片操作
切片(slice)重载:
切片重载同性索引重载公用的方法
getitem(self, i) 切片取值 isinstance(i, slice)
setitem(self, i, v) 切片赋值
delitem(self, i) del切片删除
以下代码是一个链表的取值重写

def __getitem__(self, i):
    cur_node = self._head

    if isinstance(i, slice):
        if not isinstance(i.start, int) and not i.start is None:
            raise TypeError('slice indices must be integers or None')
        if not isinstance(i.stop, int) and not i.stop is None:
            raise TypeError('slice indices must be integers or None')
        if not isinstance(i.step, int) and not i.step is None:
            raise TypeError('slice indices must be integers or None')
        start = i.start or 0
        stop = i.stop or len(self)
        forward = stop - start
        step = i.step or 1
        result = LinkedListR()
        while start:
            try:
                cur_node = cur_node.next
            except AttributeError:
                return result
            start -= 1
        while forward:
            try:
                result.append(cur_node.elem)
                for i_step in range(step):
                    cur_node = cur_node.next
            except AttributeError:
                return result
            forward -= step
        return result

    if not isinstance(i, int):
        raise TypeError('list indices must be integers')
    while i:
        try:
            cur_node = cur_node.next
        except AttributeError:
            raise IndexError('list index out of range')
        i -= 1
    if cur_node is None:
        raise IndexError('list index out of range')
    return cur_node.elem

-----------------------------------------------------------------迭代器重载
迭代器:
next(self):
可迭代对象:
iter(self):
-----------------------------------------------------------------with环境管理器类内重载
类内有__enter__ 和 exit 方法的类被称为环境管理器
能够用with进行管理的对象必须是环境管理器
enter 方法将在进入 with 语句时被调用返回由 as 变量管理的对象
exit 方法将在离开with语句时被调用,且可以用参数来判断离开with语句时是否有异常发生并作出相应的处理

猜你喜欢

转载自blog.csdn.net/syqnyue/article/details/87604743