Object Oriented Programming in Python

lets take line 19 and 20, in OOP when do you know when to add self like should l say self.student or student?


self is a keyword that essentially takes the role of being a class, the class being the current instance. So if you had for example:

english = Course('English', 30)

You would get the name property like so:

course_name = english.name
# prints 'English'

However what happens if you need to access the properties from within the class instance? You need some way to refer to the name property for the English instance before it exists. That’s where self comes in. self essentially takes the place of wherever you want the class to refer to itself. So in the case of:

def add_student(self, student):
   if len(self.students) < self.max_students:

The way you know when to use self is by when you need to refer to the property and when you need to refer to the passed variable student. So the students property is a list for that class of students taking the class. Therefore you can only add a new student if there’s room, that logic is reasonable. So you have to tell python “for the current class, check if we have room for a new student”.
Since the list students and the integer max_students are both properties of the class, you need to refer to them using the class property notation which is self.students and self.max_students. Here we are using self.students in place of where we would use english.students outside the class to call the property value.

To sum up, essentially self is a substitute for the class name when used specifically inside of the class definition, and is used whenever you need to refer to a property of the class from inside of itself.

1 Like

doesn’t self represent the instance

What is english.students?

Correct yes, self is a representation of the instance, which means you use it when you would want to access a class property, but it is within the class definition.

As for this, I have used the Course class definition in the video, and created an example in my last message of a class instance called “english” to demonstrate the point.

ok l get it now

Another question, is class attribute same as class variable


Yes they are the same, it’s just two different ways of referring to what is essentially the same thing.

1 Like