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
Y B
14,136 PointsBasic OOP question
I obviously didn't listen closely enough in the python OOP course as I fail to see what the issue is with this very simple question - can anyone help?
class Person:
def __init__(self, name):
self.name = name
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, name)
5 Answers
Trevor Currie
9,289 PointsY B,
When you call the method greet, you need to essentially remind the method where its getting the variable name from. If you had written something like,
def greet(self, other_name, name):
return "Hi {0}, my name is {1}".format(other_name, name)
The method would greet you other_name with any identity you want; however, since you want to greet other_name with the object's own name. You need to tell the method the name is coming from data stored inside the object.
def greet(self, other_name):
return "Hi {0}, my name is {1}".format(other_name, self.name)
William Li
Courses Plus Student 26,868 PointsIt's about the missing self.
return "Hi {0}, my name is {1}".format(other_name, self.name)
William Li
Courses Plus Student 26,868 PointsI suggest that you go back to watch the videos more, you need to pay closed attention to Kenneth Love 's lectures, some of them can be quite fast-paced.
I think the problem of your codes is due to that you haven't had a firm understanding of the self keyword, and when to use it when writing a class. self is a very important construct in Python OOP, if you don't know it well, you can't follow along in the rest of the course.
Kenneth Love
Treehouse Guest TeacherSpeed/length is an issue I'm still working on :)
William Li
Courses Plus Student 26,868 Pointsactually, Kenneth, I like your speed, for other teachers in Treehouse, I often need to speed up video to 1.25x-1.50x, but I play your lectures at normal speed, which is perfect. :P
Y B
14,136 PointsThanks for your answer but unfortunately I'm still non the wiser. I'm broadly comfortable of the use of self as a reference to the instance but still can't see what the obvious mistake is in the above code?
Y B
14,136 PointsThanks for the help - Trevor that a great help and makes, sense. I was originally being silly and defining 'name' as a global variable outside the class.
Thanks.