方法重载
operator模块提供一下特殊方法,可以将类的实例使用下面的操作符来操作
运算符 | 特殊方法 | 含义 |
<,<=,==,>,>=,!= | __lt__,__le__,__eq__,__gt__,__ge__,__ne__ | 比较运算符 |
+,-,*,/,%,//,**,divmod | __add__,__sub__,__mul__,__truediv__,__mod__,__floordiv__,__pow__,__divmod__ | 算术运算符,移位,位运算符 |
+=,-=,*=,/=,%=,//=,**= | __iadd__,__isub__,__imul__,__itruediv__,__imod__,__ifloordiv__,__ipow__ |
__sub__
class M:
def __init__(self,b):
self.b=b
def __sub__(self,other):
return M(self.b-other.b)
x=M(5)
y=M(6)
p=x-y
print(type(p),p.b)
print(x.__sub__(y).b)
class M:
def __init__(self,b):
self.b=b
def __sub__(self,other):
# return M(self.b-other.b) # new object
self.b-=other.b
return self
def __ne__(self,other):
return self.b != other.b
def __eq__(self,other):
return self.b == other.b
def __gt__(self,other):
return self.b>other.b
def __repr__(self):
return 'repr: {} => {}'.format(id(self),self.b)
def __iadd__(self,other): # inplace add
# return M(self.b+other.b) # 新object,地址发生改变
self.b+=other.b
return self # 仍旧为原object
x=M(5)
y=M(6)
z=M(4)
v=z
print(x==y)
print(x!=y)
print(y==z)
print(y!=z)
print(v==z)
print(sorted([x,y,z],key=lambda x:-x.b)) # key优先级高
print(x)
x+=y
print(x)
int
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def add(self,other):
return Point(self.x+other.x,self.y+other.y)
def __add__(self,other):
return (self.x+other.x,self.y+other.y)
def __eq__(self,other):
if self is other:
return True
return self.x==other.x and self.y==other.y
def __str__(self):
return 'Point: {} : {}'.format(self.x,self.y)
p1=Point(2,2)
p2=Point(2,2)
points=(p1,p2)
print(points[0].add(points[1]))
print(points[0]+points[1])
print(Point(*(points[0]+points[1])))
print(p1==p2)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律