Understanding init() Method and 'self ' Parameter


Note: Read after watching the lecture

Here self is referred to s1 and s2 so instead of writing the same method for 2 different objects, we utilized the same for all objects.

Here is a quick read that should help you to understand init method, https://micropyramid.com/blog/understand-self-and-__init__-method-in-python-class/

Basically, __init__ is used to initialize the attribute of a class whenever we create an instance. When we work with classes we deal with different instances. Here in our lecture example, we created s1 and s2, similar if we have more students, we create more instances. 

self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

So when I call s1.display(), indirectly we call display(s1), here we replaced self with s1 and get all details about s1.name, s1.age. For same reason, we are not passing values to display() directly, we first need to combine them for that specific instance, we do that using self.name in init

Discussion

33 comments