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

Sebastiaan Stoffels
Sebastiaan Stoffels
3,075 Points

Object Oriented Python - Inheritance Quiz

Hi there, Just making my way through the new Object Oriented Python course, and wanted to check my understanding on something. I'm on the section covering Inheritance, and on Quiz question 4 of 5 the following question is posed:

The following code:

class Orange(Fruit):
    has_pulp = True

    def squeeze(self):
        return has_pulp

Orange().squeeze() will return True

The answer is false, but I want to know why. The only thing I could find is that the function definition for squeeze() is missing the 'self' part, i.e. it should be:

def squeeze(self):
    return self.has_pulp

In which case, it would return True

Am I right that is the reason? Or is there another 'learning' from this particular question.

3 Answers

Christopher Shaw
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Christopher Shaw
Python Web Development Techdegree Graduate 58,236 Points

Self refers to the current instance of the class. In your first code, the has_pulp without self is not the same vaiable as the class variable definded earlier. With self.has_pulp now refers to the class variable.

no you are right if it was self.has_pulp then it will be true

It gives error right? Orange() is not a class, but an instance acutally: Orange is a class while Orange() is an instance. But the Orange class doesn't have self.has_pulp, so asking for it produces an error. I think Orange.squeeze() doesn't work either because you need to pass an instance of Orange. So Orange.squeeze(Orange()) works. Am I correct on all these?

Orange.squeeze(Orange()) doesn't work. I guess making attribute like self.attribute is important.