#魔术方法(二)——用于比较的魔术方法
#有时候我们需要比较两个对象。比如哪个对象大,哪个对象小。如果我们
#不告诉python如何比较,那么Python是不知道如何进行比较的。这时候
#我们需要使用一些魔术方法来达到我们的需求。
#__eq__(self,other)魔术方法:
#在使用==比较运算符比较两个对象是否相等的时候会调用这个方法。
#如果是相等,那么应该返回True,否则返回False。
#__ne__(self,other)魔术方法:
#在使用!=比较运算符来比较两个对象是否不相等的时候会调用这个方法。
#如果这两个对象不想等,那么应该返回True,否则返回False。
#__lt__(self,other)魔术方法:
#在使用<比较运算符来比比较两个对象大小的时候会调用这个方法。
#如果self<other,那么应该返回True,否则返回False。
#<=和>=的解决方案:
#以上讲了<、>、==以及!=的执行方法。
#没有讲<=和>=这两个运算符执行的方法,其实这两个方法是这样执行的,
#拿<=为例来讲,首先执行<判断,如果为False,那么会再执行==判断,
#如果都为False,那么就返回False。
class Person(object):
def __init__(self,age,height):
self.age = age
self.height = height
def __eq__(self,other):
if self.age==other.age and self.height==other.height:
return True
else:
return False
def __ne__(self,other):
if self.age!=other.age or self.height!=other.height:
return True
else:
return False
def __lt__(self,other):
if self.age < other.age:
return True
else:
if self.age==other.age:
return True if self.height<other.height else False
else:
return False
def __gt__(self,other):
if self.age>other.age:
return True
else:
if self.age==other.age:
return True if self.height>other.height else False
else:
return False
p1=Person(18,170)
p2=Person(18,180)
if p1>p2:
print(True)
else:
print(False)
Python中的魔术方法(二)——用于比较的魔术方法
最新推荐文章于 2022-09-16 00:09:49 发布