方法重载

  

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)

 

posted @ 2020-10-05 23:22  ascertain  阅读(97)  评论(0编辑  收藏  举报