面向对象-内置特殊方法-对象比较。
class Child:
def __init__(self, age, height):
self.age = age
self.height = height
def __eq__(self, other): # 等于
print(other)
return self.age == other.age
def __ne__(self, other): # 不等于
print('不等于')
return self.age != other.age
def __gt__(self, other): # 大于
return self.age > other.age
def __ge__(self, other): # 大于等于
return self.age >= other.age
def __lt__(self, other): # 小于
return self.age < other.age
def __le__(self, other): # 小于等于
return self.age <= other.age
a1 = Child(22, 156)
a2 = Child(23, 164)
print(a1 == a2)
print(a1 != a2) # 等于功能完善后不等于也就相应实现了,但是也可以单独去使用__ne__()去单独处理
# 通过比较运算符,把左边的值赋值给self,右边的赋值给other
a1 = Child(22, 156)
a2 = Child(23, 164)
print(a1 == a2)
print(a1 != a2) # 等于功能完善后不等于也就相应实现了,但是也可以单独去使用__ne__()去单独处理
# 通过比较运算符,把左边的值赋值给self,右边的赋值给other
# 有了>, ==, >=之后就可以通过下面的装饰器,同步实现<, !=, <=,反过来也是一样的,
# 同时还能把>=拆分为>和=,<=拆分为<和=,反过来也能把<和=组合成<=
# import functools
# @ functools.total_ordering
# 通过下面代码就能查看
print(Child.__dict__)