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.

Nicolae Laurentiu
1,538 PointsHy, I don't understand why the code doesn't run
class Fruit:
test = "test"
class Orange(Fruit):
has_pulp = True
def squeeze(self):
return has_pulp
print(Orange().squeeze())
[MOD: added ```python formatting -cf]
2 Answers

Chris Freeman
Treehouse Moderator 67,986 PointsThe error in running your code is:
Traceback (most recent call last):
File “<string>”, line 12, in <module>
File “<string>”, line 9, in squeeze
NameError: global name ‘has_pulp’ is not defined
To reference the 'has_pulp' attribute of a class instance
, the instance needs to be referenced. The parameter self
is used to point to the current instance. Using self.has_pulp
will fix the error.
Post back if you need more help. Good luck!!!

Mark Chesney
11,698 PointsI'm very interested in how this works. I'm normally used to doing OOP like so:
mandarin_orange = Orange()
mandarin_orange.squeeze()
I didn't know it was even possible to do Orange().squeeze()
(of course, if the self.has_pulp
attribute were correctly implemented). Would you call this a method call directly on the class, rather than an instantiated object's method call (as would be mandarin_orange.squeeze()
) ?
feeling kinda confused but kind of learning

Chris Freeman
Treehouse Moderator 67,986 PointsGood question! The key is in the parens.
The Orange
() in Orange().squeeze()
is creating an instance of the class, then calling the squeeze
method of that instance. The parens call the class to create the instance.
If the parens are removed, then an error is raised because self
doesn’t exist until the class instance wasn’t created. Without parens, it would be calling a classmethod.
Decorating a method with @classmethod
allows access before the instance is created.
class Fruit:
test = "test"
class Orange(Fruit):
has_pulp = True
def squeeze(self):
return self.has_pulp
@classmethod
def squeeze2(cls):
return cls.has_pulp
print(Orange().squeeze())
print(Orange.squeeze2())
# prints
# True
# True