4. 比较运算符的重载
运算符和方法
方法名
运算符和表达式
说明
__lt__(self, other)
self < other
小于
__le__(self, other)
self <= other
小于等于
__gt__(self, other)
self > other
大于
__ge__(self, other)
self >= other
大于等于
__eq__(self, other)
self == other
等于
__ne__(self, other)
self != other
不等于
比较运算符通常返回布尔值 True 或 False。
示例
# 比较运算符重载 示例
# http://weimingze.com
class Vector1D:
'''用于描述一维向量的类!'''
def __init__(self, x):
self.x = x
def __repr__(self):
return f'Vector1D({self.x})'
def __lt__(self, other): # lt : little than
# print('__lt__:小于号运算符重载')
return self.x < other.x
def __le__(self, other): # le : little equal
# print('__le__:小于等于号运算符重载')
return self.x <= other.x
def __gt__(self, other):
# print('__gt__:大于号运算符重载')
return self.x > other.x
def __ge__(self, other):
# print('__ge__:大于等于号运算符重载')
return self.x >= other.x
def __eq__(self, other):
# print('__eq__:等于号运算符重载')
return self.x == other.x
def __ne__(self, other):
# print('__ne__:不等于号运算符重载')
return self.x != other.x
v1 = Vector1D(100)
v2 = Vector1D(200)
print("v1:", v1)
print("v2:", v2)
print(v1 < v2)
print(v1 <= v2)
print(v1 > v2)
print(v1 >= v2)
print(v1 == v2)
print(v1 != v2)
运行结果
v1: Vector1D(100)
v2: Vector1D(200)
True
True
False
False
False
True
比较运算符重载说明
当没有与之相对的方法时,则采用对应的方法取值后再取非后返回。
方法名
运算符
对应方法名
对应运算符
__lt__(self, other)
<
__gt__(self, other)
>
__le__(self, other)
<=
__ge__(self, other)
>=
__eq__(self, other)
==
__ne__(self, other)
!=
当既没有
__eq__(self, other)
方法,也没有__ne__(self, other)
方法时,将判断两个对象的ID是否相同,如果相同返回True,如果不同返回False。
详细说明
-
大于运算符(>) 的重载方法是__gt__,当没有__gt__方法时,将调用__lt__方法获取值后取非(not),如果再没有__lt__方法会触发TypeError类型错误。
-
小于运算符(<) 的重载方法是__lt__,当没有__lt__方法时,将调用__gt__方法获取值后取非(not),如果再没有__gt__方法会触发TypeError类型错误。
- 小于运算符的重载与大于运算符的重载相反;
-
大于等于运算符(>=) 的重载方法是__ge__,当没有__ge__方法时,将调用__le__方法获取值后取非(not),如果再没有__le__方法会触发TypeError类型错误。
-
小于等于运算符(<=) 的重载方法是__le__,当没有__le__方法时,将调用__ge__方法获取值后取非(not),如果再没有__ge__方法会触发TypeError类型错误。
- 小于等于运算符的重载与大于等于运算符的重载相反;
-
等于运算符(==) 的重载方法是__eq__,当没有__eq__方法时,将判断两个运算符的ID是否相同,如果相同返回True,如果不同返回False。
-
不等于运算符(!=) 的重载方法是__ne__,当没有__ne__方法时,将调用__eq__方法获取值后取非(not),如果再没有__eq__方法,则判断两个运算符的ID是否相同,如果不同返回True,如果相同返回False。