The self parameter in Python represents the current object of a class.
It allows a class method to:
-
access instance variables
-
call other methods of the same object
-
differentiate between object data and local variables
What is Self ?
self is a reference to the object that is currently calling the method.
When you call a method using an object, Python automatically passes the object reference as self.
Why self is Required ?
Without self, Python cannot know:
-
which object is calling the method
-
where to store or retrieve instance data
Each object has its own memory, and self points to that memory.
Using Self to Access Instance Variable :
Python
class Student: def set_details(self, name, age): self.name = name self.age = age def show(self): print(self.name, self.age) s1 = Student() s1.set_details("Rahul", 22) s1.show() #output Rahul 22 Classing Methods with self :
Python
class Person: def __init__(self, name): self.name = name def greet(self): return "Hello, " + self.name def welcome(self): message = self.greet() print(message + "! Welcome to our website.") p1 = Person("Rahul") p1.welcome() #output Hello, Rahul! Welcome to our website.