2016-04-25 36 views
2

问题有关Python操作首要:__ge__(对应于 '> =')结果未如预期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 

结果一个控制台是:

766.3 
False 
True 

最后一条语句显然是不正确的:381.3> 385和381.3> = 385显然都是假的,但最后打印的行是真的。

这是由这个Book类中的实现错误还是Python的一些内部错误引起的?我正在使用Python 2.7.10.3

+3

也许你应该使用'other.pages'而不是将一个数字与一个对象进行比较 –

回答

5

问题是一个错字:___le__()应该是__le__()

但是,这是实现比较运算符的一种非常不寻常的方式。通常你会比较两个相同类型的对象,而不是将一个数字与一个Book对象进行比较。这就是为什么这是如此令人困惑:>运营商实际上是调用__lt__()方法,而>=没有找到__le__()方法。方向相反的原因是比较运算符左侧的数字没有实现丰富的比较方法,但右侧的Book确实如此。这会导致reversed comparison method被调用。

这些方法没有交换参数版本(当左侧参数不支持该操作,但右侧参数时使用);相反,__lt__()__gt__()是彼此的反映,__le__()__ge__()是彼此的反映,而__eq__()__ne__()是他们自己的反映。

我认为如果班级刚刚实施__cmp__()会更容易理解。