self in Python
The “self” parameter represents the current object (instance) of the class.
- It allows each object to keep track of its own data (attributes).
- It must be the first parameter of any instance method inside a class (Python passes it automatically when you call a method).
Example: Without self. Imagine we define a method without self:
Python
class Student:
def introduce():
print("Hello, I am a student")
s1 = Student()
s1.introduce() # ❌ TypeError (missing 1 required positional argument) This fails because Python automatically passes the object (s1) to the method, but the method doesn’t accept it.
Example: With self.
Python
class Student:
# Class attribute/variable
Company = "Google"
# Constructor
def __init__(self, name, age):
self.name = name # self refers to the current object
self.age = age
# Method
def introduce(self):
print(f"My name is {self.name}, and I am {self.age} years old. Working in the company {self.Company}.")
# Create an instance of the class
s1 = Student("Ashish", 29) # s1 is passed as self
s2 = Student("Katrina", 25) # s2 is passed as self
# change the class attribute for object s2
s2.Company = "Amazon"
# Call the method
s1.introduce()
# Output: My name is Ashish, and I am 29 years old. Working in the company Google.
s2.introduce()
# Output: My name is Katrina, and I am 25 years old. Working in the company Amazon. Here:
• When we call s1.introduce(), Python internally does:
• Student.introduce(s1)
• So, self = s1.
• When you call s2.introduce():
• Student.introduce(s2)
• So, self = s2.