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

salman khan
salman khan
1,283 Points

A little doubt in classes

class Student():
    name = 'John Wick'
    def praise(self):
        return ("you look great today {}!!".format(Student.name))

code 2

class Student():
    name = 'John Wick'
    def praise(self):
        return ("you look great today {}!!".format(self.name))

both gives the same output,but what's the different between in using 'self' and class name

pet
pet
10,908 Points

I would also like to know the reason thanks as well. :)

2 Answers

Steven Parker
Steven Parker
221,450 Points

The term "self" refers to the specific instance, and "Student" refers to the class itself. They only seem interchangeable when using them with class attributes. Otherwise, they could produce different values or possibly one could cause an error.

It's unlikely that you'd ever really want to reference the class by name from within the class. The "self" reference will be the one you want for most cases.

class.name is referring to the class (i.e. Student) you are writing. You don't have self yet. You have self when you create an instance of class Student. Once you have something like emily = Student(). Then, self is emily (or emily is self).