1.作用:可以自定义对象“比较大小,相等以及真假”规则。
2.步骤:
实现6个方法:相等__eq__,不相等__ne__,小于__lt__,小于等于__le__,大于__gt__,大于等于__ge__
class Person: # == != < <= > >= def __init__(self, age, height): self.age = age self.height = height def __eq__(self, other): print("等于判定") return self.age == other.age def __ne__(self, other): print("不等于判定") return self.height != other.height def __gt__(self, other): print("大于判定") return self.age > other.age def __ge__(self, other): print("大于等于判定") return self.age >= other.age def __lt__(self, other): print("小于判定") return self.age < other.age def __le__(self, other): print("小于定于判定") return self.age <= other.age pass p1 = Person(17, 1880) p2 = Person(17, 1990) print(p1 == p2) print(p1 != p2) print(p1 > p2) print(p1 >= p2) print(p1 < p2) print(p1 <= p2)
3.注意:如果对于反向操作的比较符,只定义了其中一个方法,但使用的是另外一种比较运算,那么解释器会采用调换参数的方式进行调用该方法。但是不支持叠加操作。
4.补充:
4.1使用装饰器,自动生成“反向”组合的方法
import functools @functools.total_ordering class Person: def __init__(self, other): pass def __lt__(self, other): pass def __eq__(self, other): pass # p1 = Person() # p2 = Person() # # p1 < p2 print(Person.__dict__)
4.2上下文环境中的布尔值__bool__
class Person: def __bool__(self): # return False return True pass p = Person() if p: print("xxxxx")