Hey @Anirudh!
Self
The self keyword is used to access the attributes and methods of the class. self just represents an instance of the class. Let's see why self is used and how it works.
Let us consider this code:
class example:
weekend = True
def isholiday(self):
if self.weekend:
print ("Today is a holiday!!")
else:
print ("Not holiday")
def change(self):
if self.weekend:
self.weekend = False
else:
self.weekend = True
a = example()
a.isholiday()
b = example()
b.change()
b.isholiday()
When an instance is created, weekend is set to True. There are 2 methods. isholiday() checks if weekend is True and if it is True, it prints "Today is a holiday!!" and if it is not True, it prints "Not holiday". And change() changes the value of weekend to False if it is True and to True if it is False. We create 2 instances 'a' and 'b' and run the methods. The output for the above code is:
#Output using self
Today is aholiday!!
Not holiday
Now we modify the above code and write it without using self:
class example:
weekend = True
def isholiday(example):
if example.weekend:
print ("Today is a holiday!!")
else:
print ("Not holiday")
def change(example):
if example.weekend:
example.weekend = False
else:
example.weekend = True
a = example()
a.isholiday()
b = example()
b.change()
b.isholiday()
And the output for this code is:
#Output without using self
Today is a holiday!!
Today is a holiday!!
In the first code, the data of only the mentioned instance was changed and the data of other instance was untouched. But in second code, the data of both the instances of class example was changed. So the self is used to access the attributes and method on that instance only.
__init__
__init__ is a reserved keyword in python used to initialize attributes of the class when an object of that class is created. It is also known as constructor in OOPC