In Python, the self keyword represents the instance of the class and is used to access variables and methods that belong to that specific object.
It allows each object to maintain its own state and helps differentiate between instance variables and local variables.
| Feature | Description |
|---|---|
| Definition | Refers to the current instance (object) of the class. |
| Used For | Accessing class attributes, instance variables, and methods inside a class. |
| Passed Automatically | It is automatically passed to instance methods when they are called. |
| Not a Keyword | self is just a naming convention — you can use another name, but using self is standard practice. |
| Scope | Available only inside class methods. |
🧩 Example 1: Basic Use of self
class Student:
def __init__(self, name, age):
self.name = name # instance variable
self.age = age # instance variable
def show(self):
print("Name:", self.name)
print("Age:", self.age)
s1 = Student("Dheeraj", 24)
s1.show()Output:
Name: Dheeraj
Age: 24Explanation:
self.nameandself.agerefer to the object’s own data.- When
s1.show()is called, Python automatically passes the objects1as the first argument to theshow()method.
🧩 Example 2: Without Using self (Incorrect Example)
class Student:
def __init__(name, age): # ❌ Missing 'self' convention
name = name
age = age
s = Student("Dheeraj", 24) # Will raise an errorOutput:
TypeError: Student.__init__() takes 2 positional arguments but 3 were givenExplanation:
Without self, Python does not know which instance the attributes belong to.
🧩 Example 3: Using self to Access Other Methods
class Calculator:
def __init__(self, num):
self.num = num
def square(self):
return self.num ** 2
def cube(self):
return self.num ** 3
def display(self):
print("Square:", self.square())
print("Cube:", self.cube())
calc = Calculator(3)
calc.display()Output:
Square: 9
Cube: 27🧩 Example 4: self Refers to Each Instance Separately
class Dog:
def __init__(self, name):
self.name = name
dog1 = Dog("Buddy")
dog2 = Dog("Max")
print(dog1.name)
print(dog2.name)Output:
Buddy
MaxEach object (dog1, dog2) has its own copy of the variable name because of self.
🔹 In Summary
selfrefers to the instance of the class and helps access instance attributes and methods.- It is automatically passed when calling instance methods.
- It ensures each object maintains its own state.
- Although you can use another name instead of
self, it is a Python convention and should always be used for clarity and consistency.
