关于Python运算符覆盖的问题:( __ge__对应于'> =')结果不符合预期
class Book:
title = ''
pages = 0
def __init__(self, title='', pages=0):
self.title = title
self.pages = pages
def __str__(self):
return self.title
def __radd__(self, other):
'''
enables book1 + book2
'''
return self.pages + other
def __lt__(self, other):
'''
less than
'''
return self.pages < other
def ___le__(self, other):
'''
less than or equals
'''
return self.pages <= other
def __eq__(self, other):
'''
equals
'''
return self.pages == other
def __ne__(self, other):
'''
not equals
'''
return self.pages != other
def __ge__(self, other):
'''
larger than or equals
'''
return self.pages >= other
def __gt__(self, other):
'''
larger than
'''
return self.pages > other
book1 = Book('Fluency', 381.3)
book2 = Book('The Martian', 385)
book3 = Book('Ready Player One', 386)
summation = sum([book1, book2, book3])
print book1 + book2
print book1 > book2
print book1 >= book2
Run Code Online (Sandbox Code Playgroud)
结果一个控制台是:
766.3
False
True
Run Code Online (Sandbox Code Playgroud)
最后一个陈述显然是不正确的:381.3> 385和381.3> = 385显然都是假的,但最后一行是真的.
这是由本书类中的实现错误引起的,还是由Python的一些内部错误引起的?我使用的是Python 2.7.10.3
问题是错字:___le__()应该是__le__().
但是,这是实现比较运算符的一种非常不寻常的方式.通常比较两个相同类型的对象,而不是将数字与Book对象进行比较.这就是为什么这是如此令人困惑的原因:>运算符实际上正在调用__lt__()方法,并且>=找不到__le__()方法.方向反转的原因是比较运算符左侧的数字没有实现丰富的比较方法,但是Book右边的数字没有.这导致反向比较方法被调用.
这些方法没有交换参数版本(当左参数不支持操作但右参数支持时使用); 相反,
__lt__()和__gt__()彼此的思考,__le__()并__ge__()在对方的反映,__eq__()并__ne__()有自己的思考.
我认为如果该课程刚刚实施,将会更容易理解__cmp__().