Python重载
哪些不能被重载?(内置类型的运算符)
不能新建运算符,智能通过重载完成
is and not or 不能被重载
1、 运算重载:(一元)
.neg(self)-------obj 取负
.pos(self)------ +obj 取正
.abs(self)------ abs(obj) 取绝对值
.invert(self)-----~obj 取反
算术运算重载(二元):
.add(self,other)-----obj+other 加法
.sub(self,other)-----obj-other 减法
.mul(self,other)-----obj*other 乘法
.truediv(self,other)-----obj/other 除法
.floordiv(self,other)-----obj//other 整除
.mod(self,other)-----obj%other 模运算
.divmod(self,other)-----divmod(obj,other) 除模
.pow(self,other)-----obj**other 求幂
.lshift(self,other)-----obj<<other 左移
.rshift(self,other)-----obj>>other 右移
.and(self,other)-----obj&other 位与
.xor(self,other)-----obj^other 位异或
.or(self,other)-----obj||other 位或
例子
add(self,other)和+是同种含义
ls = [1,2,3,4,5,6]
lt = [1,2,3,4]
print(ls+lt)
print(ls.__add__(lt))
class NewList(list):
def __add__(self,other):
new = []
for i in range(len(self)):
try:
new.append(self[i]+other[i])
except :
new.append(self[i])
return new
lss = NewList(ls)
ltt = NewList(lt)
print(print(lss.__add__(ltt))==print(lss+ltt))
print(ltt+lss)
结果:
2、其
他重载:
.lt(self,other)------- < low than
.le(self,other)------- <= low equal
.eq(self,other)------- == equal
.ne(self,other)------- != not equal
.gt(self,other)------- > great than
.ge(self,other)------- >= great equal
3、成员运算的重载
成员获取:[ ]、del、.reversed()
成员判断:in、 not in
.getitem(self,key)----- obj[k] 取值
.setitem(self,key,v)-----obj[k] = v 赋值
.delitem(self,key)-----del obj[k] 删除
.reversed(self)-----obj.reversed() 逆序
.contains(self,item)-----item in obj 成员判断
举例:
class NewList(list):
def __contains__(self,item):
s = 0
for c in self:
s+=c
if super().__contains__(item) or item == s:
return True
else:
return False
lss = NewList([6,1,2,3])
print(6 in lss,12 in lss, 8 in lss,lss.__contains__(12))
4、其他重载
Python内置函数:
repr()、str()、len()、int()、float()、complex()、round()、
bytes()、bool()、format()
.repr(self)-------repr(obj) 可以打印字符串的运算逻辑
.str(self)------- str(obj) 字符串转换的运算逻辑
.len(self)------- len(obj) 对象操作的运算逻辑
.int(self)------- int(obj) 整数转换的运算逻辑
.float(self)------- float(obj) 浮点数的运算逻辑
.complex(self)------- complex(obj) 复数转换的运算逻辑
.round(self)-------round(obj) 对象四舍五入的运算逻辑
.bytes(self)------- bytes(obj) 对象字节串转换的运算逻辑
.bool(self)------- bool(obj) 布尔运算的运算逻辑
.format(self,format_spec)----obj.format() format(obj) 对象格式化输出的运算逻辑