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 trial

Python Object-Oriented Python Inheritance Inheritance Quiz

Andrew Dani Arianto
Andrew Dani Arianto
5,983 Points

About class Orange(Fruit) in Quiz OO-Python

In a quiz about Object-Oriented Python about inheritance, there is this question about an object Orange(Fruit) with code like below.

class Orange(Fruit): has_pulp = True

def squeeze(self):
    return has_pulp

The question is "Orange().squeeze() will return True." {True or False)

I get the answer but I doubt it. I try the program in the workspace and already create the Fruit parent class. And here I encounter a problem. Why is there an error "NameError: name 'has_pulp' is not defined" ?

2 Answers

andren
andren
28,558 Points

Why is there an error "NameError: name 'has_pulp' is not defined" ?

Because has_pulp is not a variable defined within the squeeze method. It has been defined as a class attribute, to access it you have to use the self keyword.

So the code for the squeeze method should have looked like this:

def squeeze(self):
    return self.has_pulp

If it had looked like that then the answer to the Quiz would have been True, as the squeeze method would have returned True, but since it lacked the self keyword it instead results in an exception being raised.

The question is phrased in a somewhat confusing way, since the correct answer is False that might lead you to think that the code returns False rather than True, but that is not the case. The question is asking if the statement "Orange().squeeze() will return True." is correct (True) or incorrect (False) not which of those values it will return. Since the code results in an exception it is false to say that it will return True. Hence False is the correct answer to the question.