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 trialIan Cole
454 PointsHard time understanding classes
I know im doing something wrong here, most likely my syntax. But im having a super hard time wrapping my head around classes, methods, etc... Could someone help me to understand the concept? It seems kinda important.
class Student:
name = "Your Name"
def praise(self):
return "You inspire me, {}".format(self.name)
def reassurance(self):
return "Chin up, {}. You'll get it next time!".format(self.name)
def feedback(self, grade):
if grade > 50:
return praise(self)
else:
return reassurance(self)
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsYou are closer than you think! The class methods uses self
as the first parameter to hold the reference of the current instance of the class. "self" is used to keep track of the current instance and it's not something you need to pass during a method call.
So, when feedback
is called on a reference, the self
contains the current instance reference. This "self" is used to determine where to find praise
since it's not a global function. By using self.praise()
within the feedback
method, you are saying call the praise()
method that can be found in the namespace of this instance. Notice there are no arguments when calling praise()
since the instance reference is taken care of automatically.
Hope that helps. Post back if you have more questions. Good luck!!
Jeffrey James
2,636 PointsJeffrey James
2,636 PointsI think classes are sort of superflous when you're just learning Python. In the end, it's just a way to call a function on an object that you wanted to create from scratch. By object, I mean that using a string, list JSON object, something from a library, a dictionary, etc....was not enough to handle your problem by writing functions for.
Most of the examples you see in tutorials for Classes are contrived, so much so, that it all seems trite.