What is the use of self in Python?
The self keyword is used to represent the instance of a class. When you create an object from a class, self acts as a reference to that particular object. It allows you to access the attributes and methods of the object within the class.
Key Points
- self must be explicitly declared as the first parameter in instance methods.
- It provides a way to differentiate between class-level variables and instance-level variables.
Here’s a simple example:
class Student:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Creating an object of the Student class
student1 = Student("John", 20)
student1.display_info()

You can also try this code with Online Python Compiler
Run Code
Output:
Name: John, Age: 20
In this example, self is used to access and initialize the instance attributes name and age.
When to Use Self in Python
Now that we know the difference between instance methods and class methods, let's understand when and how to use the self keyword in Python.
1. Accessing Instance Variables
When you need to access or modify instance variables within a class method, you use the self keyword. By prefixing the variable name with self, you indicate that it belongs to the current instance of the class. This allows each instance to have its own copy of the variable.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I'm {self.age} years old.")
In the above code, self.name and self.age are instance variables accessed using the self keyword within the __init__ and introduce methods.
2. Calling Instance Methods
When you want to call an instance method within another method of the same class, you use the self keyword to refer to the current instance. By prefixing the method name with self, you ensure that the method is called on the correct instance.
Example:
class Calculator:
def __init__(self, value):
self.value = value
def square(self):
self.value **= 2
def calculate(self):
self.square()
print(f"Result: {self.value}")
In this example, the calculate method calls the square method using self.square() to perform the calculation on the current instance.
3. Passing Self to Other Methods
When you pass the current instance as an argument to another method or function, you use the self keyword. This allows you to pass the instance along with its associated data and behavior.
Example:
def print_person_info(person):
print(f"Name: {person.name}, Age: {person.age}")
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print_person_info(self)
In this case, the display_info method passes self as an argument to the print_person_info function, allowing it to access the instance's name and age attributes.
Python Class self Constructor
In Python, the constructor is a special method defined using __init__. The self keyword plays a crucial role here as it initializes the attributes of a class instance.
Example
class Circle:
def __init__(self, radius):
self.radius = radius # Instance attribute
def area(self):
return 3.14 * self.radius * self.radius
# Creating an object of the Circle class
circle1 = Circle(5)
print("Area of Circle:", circle1.area())

You can also try this code with Online Python Compiler
Run Code
Output:
Area of Circle: 78.5
In this example, self.radius ensures that the radius variable belongs to the specific instance of the class.
Is self in Python a Keyword?
No, self is not a keyword in Python. It is a naming convention used to represent the instance of a class. You can replace self with any other valid variable name, but using self is a widely accepted practice and improves code readability.
Example
class Book:
def __init__(this, title, author): # 'this' instead of 'self'
this.title = title
this.author = author
def display_details(this):
print(f"Title: {this.title}, Author: {this.author}")
book1 = Book("Python Basics", "Jane Doe")
book1.display_details()

You can also try this code with Online Python Compiler
Run Code
Output:
Title: Python Basics, Author: Jane Doe
While this works, it is recommended to stick with self for consistency and better readability.
self: Pointer to Current Object
The self keyword acts as a pointer to the current object. When you call a method on an object, Python automatically passes the instance to the method, allowing self to reference the object.
Example:
class Calculator:
def __init__(self, value):
self.value = value
def add(self, number):
return self.value + number
calc = Calculator(10)
print("Result:", calc.add(5))

You can also try this code with Online Python Compiler
Run Code
Output:
Result: 15
Here, self.value refers to the value attribute of the calc object.
Example: Creating Class with Attributes and Methods
Let’s look at a more comprehensive example to understand the role of self in classes with multiple attributes and methods.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def display_details(self):
print(f"Employee Name: {self.name}")
print(f"Salary: {self.salary}")
def give_raise(self, amount):
self.salary += amount
print(f"New Salary for {self.name}: {self.salary}")
# Creating an Employee object
emp1 = Employee("Alice", 50000)
emp1.display_details()
emp1.give_raise(5000)

You can also try this code with Online Python Compiler
Run Code
Output:
Employee Name: Alice
Salary: 50000
New Salary for Alice: 55000
self in Constructors and Methods
Constructors and instance methods both use self to access and modify the attributes of an object.
Example with both Constructor and Method:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display_car(self):
print(f"Car: {self.make} {self.model}")
# Creating a Car object
car1 = Car("Toyota", "Corolla")
car1.display_car()

You can also try this code with Online Python Compiler
Run Code
Output:
Car: Toyota Corolla
self: Convention, Not Keyword
Although self is a convention, adhering to it is important for writing Pythonic code. Using a different name instead of self may confuse other developers and reduce the clarity of your code. Here’s why you should follow the convention:
- Consistency with standard Python practices.
- Easier collaboration in teams.
- Better understanding for beginners following tutorials and documentation.
Example Showing Why Convention Matters:
class Gadget:
def __init__(self, name):
self.name = name
def display_name(self):
print(f"Gadget Name: {self.name}")
gadget = Gadget("Smartphone")
gadget.display_name()
Sticking to self ensures the code is consistent with Python’s ecosystem and community standards.
Python Self in Action
Now that we've discussed and understood the basics of the self keyword and when to use it, let's see some practical examples:
Example 1: Bank Account
class BankAccount:
def __init__(self, account_number, balance):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposited {amount}. New balance: {self.balance}")
def withdraw(self, amount):
if self.balance >= amount:
self.balance -= amount
print(f"Withdrawn {amount}. New balance: {self.balance}")
else:
print("Insufficient funds.")
def display_balance(self):
print(f"Account {self.account_number} balance: {self.balance}")
# Creating instances of the BankAccount class
account1 = BankAccount("123456789", 1000)
account2 = BankAccount("987654321", 500)
# Using instance methods
account1.deposit(500)
account2.withdraw(200)
account1.display_balance()
account2.display_balance()
In this example, we define a BankAccount class with instance variables account_number and balance. The __init__ method initializes these variables using the self keyword. The deposit, withdraw, and display_balance methods all use self to access and modify the instance variables.
We create two instances of the BankAccount class, account1 and account2, with different account numbers and balances. We then call the instance methods on these objects to perform actions like depositing, withdrawing, and displaying the balance.
Example 2: Rectangle
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
def calculate_perimeter(self):
return 2 * (self.length + self.width)
# Creating instances of the Rectangle class
rect1 = Rectangle(5, 3)
rect2 = Rectangle(7, 4)
# Using instance methods
area1 = rect1.calculate_area()
perimeter1 = rect1.calculate_perimeter()
print(f"Rectangle 1 - Area: {area1}, Perimeter: {perimeter1}")
area2 = rect2.calculate_area()
perimeter2 = rect2.calculate_perimeter()
print(f"Rectangle 2 - Area: {area2}, Perimeter: {perimeter2}")
In this example, we have a Rectangle class with instance variables length and width. The calculate_area and calculate_perimeter methods use the self keyword to access these variables and perform calculations specific to each instance.
We create two instances of the Rectangle class, rect1 and rect2, with different lengths and widths. We then call the instance methods to calculate the area and perimeter of each rectangle and print the results.
Frequently Asked Questions
What is the self keyword in Python?
self is a reference to the current instance of the class. It allows you to access attributes and methods within the class.
Can I use a different name instead of self?
Yes, you can use any name instead of self, but it is not recommended as self is the widely accepted convention.
Why do we use self in Python classes?
We use self to differentiate instance variables from local variables and to make it clear that the method or attribute belongs to a specific instance.
Conclusion
In this article, we discussed the self keyword in Python, its importance, and its usage in constructors and methods. You learned that self is not a keyword but a convention to represent the current object instance. By understanding and following this concept, you can write more organized and readable object-oriented code in Python.
You can also check out our other blogs on Code360.