![python3中的比较函数 python3中的比较函数](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
在py2中,比较函数是cmp,而在py3,cmp已经不存在了,Py3启用了新的比较方法
原来在py2中,a>b就会调用a对象中的__cmp__函数,而现在a>b会调用a对象中的__lt__函数。
import oprater
a=1
b=2
operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
'''
简单说下这几个函数的意思吧。
lt(a, b) 相当于 a < b
le(a,b) 相当于 a <= b
eq(a,b) 相当于 a == b
ne(a,b) 相当于 a != b
gt(a,b) 相当于 a > b
ge(a, b)相当于 a>= b
'''
class aa:
def __init__(self,k):
self.k=k def __gt__(self,b):
print ('gt',self.k)
return self.k>b.k
def __lt__(self,b):
print ('lt',self.k)
return self.k<b.k az=aa(1)
vc=aa(2)
if az>vc:
print ('gt')
print ('~~~~~~')
if az<vc:
print ('lt') '''
gt 1
~~~~~
lt 1
lt