Table of contents
1.
Introduction
2.
What are instance and class methods in Python?
3.
What is the use of self in Python?
3.1.
Key Points
4.
When to Use Self in Python
4.1.
1. Accessing Instance Variables
4.2.
2. Calling Instance Methods
4.3.
3. Passing Self to Other Methods
5.
Python Class self Constructor
5.1.
Example
6.
Is self in Python a Keyword?
6.1.
Example
7.
self: Pointer to Current Object
7.1.
Example:
8.
Example: Creating Class with Attributes and Methods
9.
self in Constructors and Methods
9.1.
Example with both Constructor and Method:
10.
self: Convention, Not Keyword
10.1.
Example Showing Why Convention Matters:
11.
Python Self in Action
11.1.
Example 1: Bank Account
11.2.
Example 2: Rectangle
12.
Frequently Asked Questions
12.1.
What is the self keyword in Python?
12.2.
Can I use a different name instead of self?
12.3.
Why do we use self in Python classes?
13.
Conclusion
Last Updated: Jan 3, 2025
Easy

Self Keyword in Python

Introduction

The self keyword is a fundamental concept in Python, especially for object-oriented programming (OOP). The self keyword in Python is used to represent the instance of the class. It allows access to the attributes and methods of the class within its own scope. When you create an object of a class, the self keyword refers to that specific object, making it possible to use and modify its attributes or call its methods.

Self Keyword in Python

In this article, we will discuss what self means, how it works, and how to use it effectively in Python classes.

What are instance and class methods in Python?

In Python, methods within a class can be categorized as either instance methods or class methods. The key difference lies in whether they operate on an instance of the class or the class itself.

Instance methods are the most common type of methods in Python classes. They are defined with the self parameter as the first argument, which refers to the specific instance of the class on which the method is called. Instance methods can access and modify the attributes of that particular instance using the self keyword.

On the other hand, class methods are defined using the @classmethod decorator and take the cls parameter as the first argument instead of self. The cls parameter refers to the class itself, rather than an instance. Class methods operate on the class level and can be called on the class directly, without needing to create an instance.

For example: 

class MyClass:
    class_var = 0
    
    def __init__(self, instance_var):
        self.instance_var = instance_var
    
    def instance_method(self):
        print(f"Instance variable: {self.instance_var}")
    
    @classmethod
    def class_method(cls):
        print(f"Class variable: {cls.class_var}")


In this example, instance_method is an instance method that accesses the instance_var attribute using self. class_method is a class method decorated with @classmethod and accesses the class_var attribute using cls.

Instance methods are used when you need to operate on a specific instance of a class, while class methods are used when you need to perform operations at the class level without requiring an instance.

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.

Live masterclass