Use of self in Python
In Python, the word 'self' is used to represent the instance of the class. We can use this to easily access the attributes and methods of the class. Let's understand in brief with an example the use of the self keyword in Python.
The 'self' keyword is used in object-oriented programming. Whenever we define a method in a class, we use 'self' as the first parameter to the function. It accesses the instance variables and methods. Here, we are taking an example of student class-
class student:
def __init__(self, name, age, standard):
self.name = name
self.age = age
self.standard = standard
def welcome(self):
print("Welcome to Lions Public School")
def info(self):
print(f"My name is {self.name}. I am {self.age} years old.")
def stud_class(self):
print(f"I study in class {self.standard}.")
In the above case, all the methods have the first parameter 'self'. The __init__() function is defined with four attributes, but when we instantiate the student class, we have to provide only three arguments. The 'self' keyword is automatically assigned with the created objects.
Let's instantiate the above class -
stud1 = student('Anjali', 16, 10)
stud2 = student('Abhi', 10, 5)
stud1.welcome()
stud1.info()
stud2.stud_class()
The above code returns the following output -
Related Articles
Canny Edge Detector OpenCV Python
Insert XML Data to MySQL Table using Python
Remove last element from list Python
Find the stop words in nltk Python
Vader Sentiment Analysis Python
isalpha Python
Python YouTube Downloader Script
Python project ideas for beginners
Pandas string to datetime
Fillna Pandas Example
Lemmatization nltk
How to generate QR Code in Python using PyQRCode
OpenCV and OCR Python
PHP code to send SMS to mobile from website
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml