I thought this would be a super simple sorting exercise but I'm not understanding the errors I'm getting.
I'm creating a simple Book class and then adding two entries. I am then sorting via sorted and using a lambda so that I sort by the isbn attribute.
books = []
class Book:
def __init__(self, title, author, isbn):
self.title, self.author, self.isbn = title, author, isbn
def __repr__(self):
return repr((self.title, self.author, self.isbn))
#add 2 items
b = Book('Russian for All', 'Chompsky', '334')
books.append(b)
c = Book('English for All', 'Zöd', '229')
books.append(c)
#sort items by the isbn number
sorted_books = sorted(books, key=lambda book: book[2])
a) I believe that __repr__ is needed so that a get a nice looking tuple for each entry when adding it to the array, as such:
print(books)
[('Russian for All', 'Chompsky', '334'), ('English for All', 'Zöd', '229')]
b) Because this looks like a standard list of tuples, using the sorted function should function without issue, but alas I get this error:
Traceback (most recent call last):
File "Untitled 2.py", line 19, in <module>
sorted_books = sorted(books, key=lambda book: book[2])
File "Untitled 2.py", line 19, in <lambda>
sorted_books = sorted(books, key=lambda book: book[2])
TypeError: 'Book' object does not support indexing
It's as if I'm seeing a nice tuple representing the objects but they're actually masking as objects which can't be accessed by the sorting function.