In Python, the keyword self is one of the most confusing things for beginners.
You see it inside every method of a class… but you never pass it manually when calling the method.
So, what is self? Why is it required? And how should you use it?
Let’s clear it up with a detailed explanation, step-by-step examples, and analogies.
🧠 What is self?
In Python, self refers to the current object (instance) of the class.
It allows:
- Accessing variables tied to that object
- Calling other methods inside the same object
- Storing unique data per object
🧠 Think of it like:
“
selfis how your object talks to itself.”
🔧 Syntax: Always the First Parameter
class Person:
def greet(self): # ← `self` is required
print("Hello!")Even though you don’t pass it explicitly when calling the method…
p = Person()
p.greet() # self is passed automatically…Python behind the scenes does this:
Person.greet(p) # 'p' becomes self✅ Why Is self Needed?
Let’s add attributes:
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, I’m {self.name}")p1 = Person("Ali")
p2 = Person("Fatima")
p1.greet() # Hello, I’m Ali
p2.greet() # Hello, I’m Fatima
self.nameallows each object to store its own name.
Without self, every object would be identical which defeats the purpose of OOP.
🧪 Real-Life Analogy
Think of a class as a form, and an object as a filled form.
self= this specific form- You write your own name, address, etc. in the form (unique per object)
🚫 Common Mistake: Forgetting self
class Car:
def drive(): # ❌ Missing self
print("Driving...")This will throw an error:
TypeError: drive() takes 0 positional arguments but 1 was given✅ Fix:
class Car:
def drive(self):
print("Driving...")✅ Best Practices
| Rule | Why? |
|---|---|
Always use self in instance methods | Python automatically passes it for you |
Name it exactly self (not this) | It’s a strong Python convention (not enforced by syntax) |
Use self.variable in methods | Keeps data tied to the current object |