使>运算符过载 (__gt__)

  • 本文关键字:运算符 python
  • 更新时间 :
  • 英文 :


我想让我的Book类重载>操作符__gt__。因此,我可以在我的BookCollection中使用它来查找正确的顺序。

我用了>在InsertBook()。但这行不通!我怎么修理它?我想让它按

排序
  1. 书的作者(字母顺序/字典顺序)
  2. 图书出版年份
  3. 书名(按字母顺序/字典顺序排列)。

这是我当前的Book.py类代码:


class Book:
def __init__(self, title='', author='',year=None):
self.title = title
self.author = author
self.year = year
def setTitle(self, title):
self.title = title
def setAuthor(self, author):
self.author = author
def setYear(self, year):
self.year = year
def getTitle(self):
return self.title
def getAuthor(self):
return self.author
def getYear(self):
return self.year
def __gt__(self,item):
if (0,1,0) > (0,0,0):
return self.author > item.author
else:
return False
if (1,0,0) > (0,0,0):
return self.title > item.title
else:
return False
if (0,0,1) > (0,0,0):
return self.year > item.year
else:
return False

def getBookDetails(self):
return "Title: {}, Author: {}, Year: {}".format(self.title, self.author, self.year)



class BookCollection():
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def insertBook(self, book):
current = self.head
previous = None
stop = False
while current != None and not stop:
if current.getData() > book:
stop = True
else:
previous = current
current = current.getNext()
temp = BookCollectionNode(book)
if previous == None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
def getNumberOfBooks(self):
temp = self.head
count = 0
while temp != None:
count = count + 1
temp = temp.getNext()
return count
def getAllBooksInCollection(self):
current = self.head
output = ""
while current != None:
output += str(current.getData()) + " "
current = current.getNext()
output = output[:len(output)-1] + "n"
return output
def getBooksByAuthor(self,item):
current = self.head
found = False
stop = False
while current != None and not found and not stop:
if current.getData() == item:
found = True
else:
if current.getData() > item:
stop = True
else:
current = current.getNext()
return found

我用了>在InsertBook()。但这行不通!我怎么修理它?我想让它按

排序
  1. 你的方法重载没有意义,为什么你比较完全静态的元组值?这总是会做同样的事情,所以你的整个重写实际上就是return self.author > item.author

  2. 单独覆盖__gt__是一个坏主意:你真的需要覆盖它们,否则你会得到不连贯的结果。functools.total_ordering类装饰器只允许重写__eq__和一个排序操作符,您可能想使用它。

我想让它按

排序
the Book’s author (alphabetical / lexicographical order)
the Book’s year of publication
the Book’s title (alphabetical / lexicographical order).

然后比较?为了简单起见,我建议使用关键方法或属性,例如

@total_ordering
class Book:
@property
def _key(self):
return (self.author, self.year, self.title)
def __eq__(self, other):
return self._key == other._key
def __gt__(self, other):
return self._key > other._key

应该按作者、出版年份和标题升序排列记录

,

Python不是Java

所有琐碎的getter和setter都是无用和多余的,直接删除它们。getBookDetails应该只是你的__str__的实现。

BookCollection同样令人担忧,isEmpty在Python中不存在,而是集合实现__len__(为了效率,还可以选择__bool__)。整个事情是一团乱,为什么BookCollection不只是包含list的书(或从stdlib的其他一些集合)?让它成为某种临时的半链表的目的是什么?

并且它应该提供(或使用)一个迭代器,你无缘无故地实现了相同的迭代方案3次。

你的命名方案也不正确,Python通常使用snake_case来命名方法、属性和字段。

最新更新