gpt4 book ai didi

Python 运算符覆盖 : __ge__ result is not as expected

转载 作者:行者123 更新时间:2023-11-28 21:47:14 35 4
gpt4 key购买 nike

关于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 类内部实现的 bug 造成的,还是 Python 的一些内部 bug 造成的?我正在使用 Python 2.7.10.3

最佳答案

问题是打字错误:__le__() 应该是 __le__()

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

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection.

我认为如果这个类只是实现__cmp__() 会更容易理解.

关于Python 运算符覆盖 : __ge__ result is not as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831616/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com