For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The self in Python is a fundamental concept that plays a key role in object-oriented programming. It is used within class methods to refer to the instance of the class. Without using self, Python would not know which object's data to operate on.
In this article, we'll break down the concept of self in Python, starting from its syntax and purpose to real-world examples. We will explore how self is used inside constructors, how it helps modify object state, and how it points to the current instance of a class. Whether you're a beginner or an advanced learner, this guide will make your understanding of self more structured and practical.
Pursue our Software Engineering courses to get hands-on experience!
In Python, self refers to the current instance of a class. It is automatically passed as the first parameter to all instance methods. When you call a method using an object, Python internally passes that object to the method as self.
This keyword allows you to access variables and methods associated with the specific object. Without self, it would be unclear which object's data is being referenced or modified. It acts as a bridge between the object and its internal data.
Take your skills to the next level with these top programs:
In Python, every instance method inside a class takes self as its first parameter. Although you do not pass it manually when calling the method, Python does it internally. This design lets the method access the attributes and other methods of the same object.
The self keyword is not a reserved keyword in Python, but by convention, it is always used as the first parameter. Replacing it with any other name will work, but doing so reduces readability and breaks standard coding practices.
Let’s understand the correct syntax using a simple example.
class Laptop:
def __init__(self, brand, price):
# Using 'self' to bind parameters to instance variables
self.brand = brand
self.price = price
def show_details(self):
# Accessing instance variables using 'self'
print(f"Laptop Brand: {self.brand}")
print(f"Laptop Price: ₹{self.price}")
# Creating an object of the Laptop class
l1 = Laptop("Dell", 55000)
# Calling the method using the object
l1.show_details()
Output:
Laptop Brand: Dell
Laptop Price: ₹55000
Explanation:
The syntax of self in Python ensures each method has access to the object's current state. It’s what makes object-oriented programming in Python both flexible and powerful.
Also Read: 16+ Essential Python String Methods You Should Know (With Examples) article!
In object-oriented programming with Python, self is essential. It ensures that every method within a class can access and manipulate the data specific to the object on which it is called. Without self, the method would not know which object's attributes it should work with.
Python passes self automatically to instance methods when you call them using an object. It links the class method to the specific object that called it. This is what allows different objects to hold different values for the same variables.
Here’s an example to show why self is important in Python.
Example: How self Keeps Object Data Separate
class Student:
def __init__(self, name, grade):
# Using 'self' to bind the parameters to object attributes
self.name = name
self.grade = grade
def display(self):
# Displaying the values specific to each object
print(f"Student Name: {self.name}")
print(f"Student Grade: {self.grade}")
# Creating two different student objects
s1 = Student("Amit", "A")
s2 = Student("Riya", "B")
# Calling the display method for each object
s1.display()
s2.display()
Output:
Student Name: Amit
Student Grade: A
Student Name: Riya
Student Grade: B
Explanation:
Why self is needed:
Must Explore: Break Statement in Python: Syntax, Examples, and Common Pitfalls
The best way to understand how self works is through examples. We will explore self in Python at different difficulty levels — from using it in constructors to modifying object state and understanding how it references the current object. Each example shows how self helps in building object-oriented programs in Python.
In this example, we’ll use self inside the constructor to assign values to instance variables. This is usually the first place you will encounter self in Python.
class Employee:
def __init__(self, name, department):
# 'self' refers to the instance being created
self.name = name # Assign name to the instance
self.department = department # Assign department to the instance
def show_details(self):
# Access instance attributes using 'self'
print(f"Name: {self.name}")
print(f"Department: {self.department}")
# Creating an object of the Employee class
emp1 = Employee("Neha", "HR")
emp1.show_details()
Output:
Name: Neha
Department: HR
Explanation:
Here, we will use self to update the internal state of an object after it has been created.
class BankAccount:
def __init__(self, account_holder, balance):
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
# Modifying balance using 'self'
self.balance += amount
def show_balance(self):
print(f"{self.account_holder}'s Balance: ₹{self.balance}")
# Creating a bank account object
acc1 = BankAccount("Ravi", 10000)
# Modifying state with deposit
acc1.deposit(2500)
acc1.show_balance()
Output:
Ravi's Balance: ₹12500
Explanation:
Also read the Reverse String in Python article!
In this advanced example, we’ll show that self refers to the current object. We'll also compare two objects using self.
class Box:
def __init__(self, length, width):
self.length = length
self.width = width
def is_same(self, other_box):
# 'self' refers to the current object
return self.length == other_box.length and self.width == other_box.width
# Creating two box objects
box1 = Box(10, 5)
box2 = Box(10, 5)
box3 = Box(8, 4)
# Comparing objects using method that uses 'self'
print("Box1 is same as Box2:", box1.is_same(box2))
print("Box1 is same as Box3:", box1.is_same(box3))
Output:
Box1 is same as Box2: True
Box1 is same as Box3: False
Explanation:
These examples make it clear how essential the self keyword is in Python. From initializing attributes to updating and comparing object data, self gives Python classes their dynamic, object-specific behavior.
You should use self in Python whenever you're working with instance methods or instance variables inside a class. It helps ensure that each object can access or modify its own data, separate from other instances. Without self, your code would not know which specific object is being referred to.
Most commonly, you’ll use self in constructors, regular methods, and while accessing or updating attributes that belong to an object. If a method needs to interact with the object’s state, then self is necessary.
Let’s understand the right use case through a simple example.
Example: When to Use self Inside a Class
class Product:
def __init__(self, name, price):
# Storing values in instance variables using 'self'
self.name = name
self.price = price
def apply_discount(self, percent):
# Using 'self' to modify the instance's price
self.price = self.price - (self.price * percent / 100)
def show_product(self):
# Displaying updated details
print(f"Product: {self.name}")
print(f"Price after discount: ₹{self.price}")
# Creating an object of Product
p1 = Product("Smartphone", 20000)
# Applying discount using method that uses 'self'
p1.apply_discount(10)
p1.show_product()
Output:
Product: Smartphone
Price after discount: ₹18000.0
Explanation:
To sum it up, you should use self in Python:
While learning object-oriented programming in Python, many developers make mistakes with the self keyword. These errors often lead to unexpected outputs or runtime exceptions. Understanding these issues early will help you avoid bugs and write cleaner code.
Let’s go through some common mistakes one by one with examples and explanations.
When defining instance methods, you must include self as the first parameter. If omitted, Python throws a TypeError.
class Car:
def start_engine(): # Missing 'self' here
print("Engine started")
# Creating an object
c = Car()
c.start_engine()
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 7, in <module>
TypeError: Car.start_engine() takes 0 positional arguments but 1 was given
Explanation:
Must read the Exception Handling in Python article!
You must use self to access instance variables inside a method. Otherwise, Python assumes you're referring to a local variable.
class Car:
def start_engine(): # Missing 'self' here
print("Engine started")
# Creating an object
c = Car()
c.start_engine()
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
File "<main.py>", line 6, in show_name
NameError: name 'name' is not defined. Did you mean: 'self.name'?
Explanation:
Also read the Variables and Data Types in Python [An Ultimate Guide for Developers] article!
You can only use self inside class methods where it’s defined. Trying to use it outside of the proper context will raise an error.
class Book:
def set_title(self, title):
self.title = title
# Trying to use 'self' outside the class
print(self.title) # 'self' is not defined here
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 6, in <module>
NameError: name 'self' is not defined
Explanation:
Avoid naming another variable self. It’s not a reserved keyword, but using it incorrectly can lead to hard-to-debug logic errors.
class Pen:
def __init__(self, color):
self.color = color
def get_color(self):
self = "Red" # Overwriting 'self'
return self.color # Trying to access attribute from a string
p = Pen("Blue")
print(p.get_color())
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
File "<main.py>", line 7, in get_color
AttributeError: 'str' object has no attribute 'color'
Explanation:
Must Read: Python Keywords and Identifiers article!
Follow these best practices:
Understanding these common errors with self in Python will help you debug faster and build more reliable Python classes.
Understanding the role of self in Python is essential for mastering object-oriented programming. It allows each object to maintain its own state and behavior. Without self, instance methods cannot access or modify object-specific data.
By consistently using self, your Python classes will work as expected and your code will be easier to understand and maintain. Keep practicing, and self will soon become a natural part of your Python programming toolkit.
In Python classes, self represents the current instance of the class. It allows access to the attributes and methods of that specific object. Without self, Python wouldn’t know which object's data or behavior you want to interact with.
Yes, technically, you can use any name instead of self for the first parameter. However, using self is a strong convention in Python, making code more readable and understandable for other programmers. It is best practice to stick to self.
self refers to instance variables, which are unique to each object. Class variables, on the other hand, belong to the class itself and are shared among all instances. Modifying instance variables via self affects only that object, not others.
Yes, Python automatically passes the instance as the first argument to instance methods. When you call a method on an object, Python sends the object itself as the self parameter behind the scenes.
No, self is not used in static methods because these methods do not receive an instance as the first parameter. Instead, class methods use cls to refer to the class, while static methods neither use self nor cls.
In inheritance, self lets child classes access and modify attributes or methods inherited from parent classes. When overriding methods, self ensures the method operates on the correct instance of the child class, maintaining polymorphic behavior.
Yes, forgetting to prefix attributes or methods with self can cause Python to treat them as local variables. This often leads to bugs that don't raise errors immediately but cause incorrect behavior or data loss in objects.
You call another method inside the same class by prefixing it with self.. For example, self.other_method() ensures that the call operates on the current object, maintaining consistency across method interactions.
Using self itself doesn't increase memory usage; it is just a reference to the current object. However, the instance variables accessed via self consume memory based on what data they store for each object.
Think of self as a label on a package. Each package has its own label (instance), allowing you to identify and interact with the right package. Similarly, self labels each object so Python knows which object's data or behavior to work with.
Using self clearly shows that a variable or method belongs to an instance. This makes code easier to read and understand because it visually distinguishes between instance attributes and local variables.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.