类的魔术方法之比较符号

from functools import total_ordering

@total_ordering#实现比较大小的方法,全写太麻烦,使用该装饰器可大大简化代码,但要求__eq__必须实现,其他方法__it__,__le__,__gt__,__ge__实现其一
class Bj():
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __eq__(self,other):#对应==操作符,判断2个对象是否相等,返回bool值
        return self.x==other.x and self.y==other.y
    def __lt__(self,other):
        return self.x+self.y < other.x+other.y
    
a=Bj(1,5)
b=Bj(2,4)

print(a==b)
print(a<b)
print (a>=b)

  结果

False
False
True

  

posted @ 2019-03-10 18:30  RealPython  阅读(225)  评论(0)    收藏  举报