3.1.2 比较
在python2中,类可以定义一个__cmp__()方法,它会根据这个对象小于、等于或者大于所比较的元素而分别返回-1,0或1。python2.1引进了富比较(rich comparision)方法
API(lt() ,le(),eq(),ne(),gt()和__ge__()),可以完成一个比较操作并返回一个布尔值。python3废弃了__cmp__()而代之以这些新方法,另外functools提供了一些工具,从而能更容易地编写符合新要求的类,即符合python3中新的比较需求。
3.1.2.1 富比较
设计富比较API是为了支持设计复制比较的类,以最高效的方式实现各个测试。不过,如果比较相对简单的类,就没有必要手动地创建各个富比较方法了。total_ordering()类修饰符可以为一个提供了部分方法的类增加其余的方法。
import functools
import inspect
from pprint import pprint
@functools.total_ordering
class MyObject:
def __init__(self,val):
self.val = val
def __eq__(self,other):
print(' testing __eq__({},{})'.format(self.val,other.val))
return self.val == other.val
def __gt__(self,other):
print(' testing __gt__({},{})'.format(self.val,other.val))
return self.val > other.val
print('Nethods:\n')
pprint(inspect.getmembers(MyObject,inspect.isfunction))
a = MyObject(1)
b = MyObject(2)
print('\nComparisons:')
for expr in ['a < b','a <= b','a == b','a >= b','a > b']:
print('\n{:<6}:'.format(expr))
result = eval(expr)
print(' result of {}:{}'.format(expr,result))
这个类必须提供__eq__()和另外一个富比较方法的实现。这个修饰符会增加其余方法的实现,它们会使用所提供的比较。如果无法完成一个比较,这个方法应当返回notImplemented,从而在另一个对象上使用逆比较操作符尝试比较,如果仍无法比较,便会完全失败。
运行结果:
注:
gt 意思是greater than(大于)
ge 意思是greater and equal(大于等于)
eq 意思是equal(等于)
le 意思是less and equal(小于等于)
lt 意思是less than(小于)
ne 相当于 a != b