I'm writing a class in Python that keeps track of a selection of books. There are three instance variables: author
, title
, and book_id
. There are four methods:
__init__(self, author, title, book_id)
: (constructor; instantiates all instance variables.)__str__(self)
: returns string representation with this format
Book("Homer", "The Odyssey", 12345)
__repr__(self)
: returns same string representation as __str__
__eq__(self, other)
determines if book itself is equivalent to the other book by checking if all three instance variables are the same. Returns a bool
.I've reached a road block. Here is the code I have so far I have gotten a good start. For some reason I keep getting indent errors with the return for the __repr__
method. If anyone familiar with writing classes has any advice I'd appreciate it.
class Book:
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
def __str__(self):
return 'Book(author, title, book_id)'
def __repr__(self):
return 'Book(author, title, book_id)'
def __eq__(self, other):
#Not sure if this is the right approach
for title in Book:
for title in Book:
if title == title:
if author == author:
if book_id == book_id:
return True
First, you are not implementing well the method __eq__
. Second you are not, returning the data you have in your book, but just a string 'Book(author, title, book_id)'
. I hope this solves your problem.
class Book:
def __init__(self, author, title, book_id):
self.author = author
self.title = title
self.book_id = book_id
def __str__(self):
return 'Book({}, {}, {})'.format(self.author, self.title, self.book_id)
def __repr__(self):
return 'Book({}, {}, {})'.format(self.author, self.title, self.book_id)
def __eq__(self, other):
return self.title == other.title and self.author == other.author and self.book_id == other.book_id