Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialsa,m cohn
Courses Plus Student 2,010 PointsHello, I keep receiving a NameError when trying to complete a task even though I've clearly defined the class.
I am completing a task where I create a eq method to check if the author and title of a book are the same and then return true if they are and false if they aren't. When I run the code, I keep getting a NameError saying I haven't defined Book, even though I did at the top of my code with a class. Can I get some help?
class Book:
def __init__(self, author, title):
self.author = author
self.title = title
def __str__(self):
return f'{self.author}, {self.title}'
def __eq__(self, other):
if isinstance(other, Book):
return self.author == other.author and self.title == other.title
return False
from book import Book
class BookCase:
def __init__(self):
self.books = []
def add_books(self, book):
self.books.append(book)
1 Answer
Steven Parker
231,269 PointsOddly, this seems to work fine in the workspace.
But in general, you want to avoid referencing a class by name from inside its own code. So instead of Book
, you can compare to self.__class__
instead.
Also, the "isinstance" check is a nice touch but isn't necessary for the challenge.