View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding Self in Python with Examples

Updated on 28/05/20254,719 Views

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!

What is self in Python?

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:

Syntax of self in Python

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:

  • def __init__(self, brand, price): The constructor method where self refers to the newly created object. It allows the object to store brand and price.
  • self.brand = brand and self.price = price: These lines store values in instance variables unique to each object.
  • def show_details(self): A regular instance method that uses self to access the data stored during initialization.
  • l1.show_details(): Even though we don't pass self explicitly here, Python internally converts this call to Laptop.show_details(l1).

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!

Why is self Needed in Python?

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:

  • Each object (s1 and s2) holds its own data: self.name and self.grade store values independently for each object.
  • The display() method uses self: It accesses the values tied to the specific object that called the method.

Why self is needed:

  • Ensures that data is not shared across objects unless intended
  • Allows the method to operate on the correct instance
  • Keeps class methods flexible and reusable across multiple objects.

Must Explore: Break Statement in Python: Syntax, Examples, and Common Pitfalls

Self in Python Examples

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.

Basic Level: Using self in the Constructor (__init__ Method)

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:

  • The __init__ method initializes object properties.
  • self.name and self.department store values for that specific instance.
  • The show_details() method uses self to access those stored values.

Intermediate Level: Modifying Class State with self

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:

  • The deposit() method uses self.balance to update the balance.
  • self ensures the balance of the correct object gets modified.
  • Each account can now maintain its own independent state.

Also read the Reverse String in Python article!

Advanced Level: self as a Pointer to the Current Object

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:

  • The method is_same() compares the current object (self) with another object.
  • self.length and self.width access the values of the object that called the method.
  • The example shows how self acts like a pointer to the calling instance.

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.

When Should You Use self in Python?

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:

  • self.name and self.price store data specific to the object p1.
  • apply_discount() uses self.price to calculate and update the discounted price.
  • Why use self here?
    • Without self, the method wouldn't know which product’s price to update.
    • It connects method logic to the correct object.

To sum it up, you should use self in Python:

  • In all instance methods, as the first parameter.
  • When accessing or modifying instance variables.
  • To differentiate between local and instance variables.

Common Errors While Using 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.

1. Forgetting to Include self as the First Parameter in Instance Methods

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:

  • Python passes the calling object as the first argument automatically.
  • Without self, the method does not expect any arguments — causing an error.

Must read the Exception Handling in Python article!

2. Accessing Instance Variables Without Using self

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:

  • The name variable without self. is treated as a local name.
  • But the actual value is stored in self.name, so it must be accessed using self

Also read the Variables and Data Types in Python [An Ultimate Guide for Developers] article!

3. Using self Outside a Class Method

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:

  • self is only meaningful inside class methods.
  • Outside methods, it is not recognized by the Python interpreter.

4. Confusing self with Other Variable Names

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:

  • Inside get_color(), the line self = "Red" reassigns self to a string.
  • Now self.color fails, since self no longer refers to the object.

Must Read: Python Keywords and Identifiers article!

How to Avoid These Mistakes?

Follow these best practices:

  • Always write self as the first argument in instance methods.
  • Use self. to refer to attributes or call other methods in the same object.
  • Never redefine self inside a method.
  • Avoid using self in static methods or outside class context.

Understanding these common errors with self in Python will help you debug faster and build more reliable Python classes.

Conclusion

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.

FAQs

1. What exactly does self represent in Python classes?

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.

2. Can we use a name other than self for the first parameter in Python methods?

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.

3. How does self differ from class variables in Python?

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.

4. Is self passed automatically when calling an instance method?

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.

5. Can self be used in static methods or class methods?

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.

6. How is self useful in inheritance and method overriding?

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.

7. Can forgetting to use self cause silent bugs?

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.

8. How do you use self to call one method from another within the same class?

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.

9. Does self affect memory usage in Python classes?

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.

10. Can you explain self with a real-world analogy?

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.

11. How does self improve code readability in Python?

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.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

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.