Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

28,521 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.