Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

What is the use of self in Python?

Last updated on Dec 05,2024 335.2K Views

3 / 62 Blog from Python Fundamentals

If you are working with Python, there is no escaping from the word “self”. It is used in method definitions and in variable initialization. The self method is explicitly used every time we define a method. In this article, we will get into the depth of self in Python in the following sequence:

Check out the Python Certification course by Edureka. This Training course is designed for students and professionals who want to be a Python Programmer. The course is designed to give you a head start into Python programming and train you for both core and advanced concepts.

What is the use of Self in Python?

Python - self in python - edureka

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. Join our Master Python programming course to know more. In Python, we have methods that make the instance to be passed automatically, but not received automatically.

Example:

class food():

# init method or constructor
def __init__(self, fruit, color):
self.fruit = fruit
self.color = color

def show(self):
print("fruit is", self.fruit)
print("color is", self.color )

apple = food("apple", "red")
grapes = food("grapes", "green")

apple.show()
grapes.show()

 

Output:

Fruit is apple
color is red
Fruit is grapes
color is green

Python Class self Constructor

self is also used to refer to a variable field within the class. Let’s take an example and see how it works:

class Person:

# name made in constructor
def __init__(self, John):
self.name = John

def get_person_name(self):
return self.name

 

In the above example, self refers to the name variable of the entire Person class. Here, if we have a variable within a method, self will not work. That variable is simply existent only while that method is running and hence, is local to that method. For defining global fields or the variables of the complete class, we need to define them outside the class methods.

Top 10 Trending Technologies to Learn in 2025 | Edureka

 

This video talks about the Top 10 Trending Technologies in 2025 that you must learn.

Is self a Keyword?

self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

self is a parameter in function and the user can use a different parameter name in place of it. Although it is advisable to use self because it increases the readability of code.

Example:

class this_is_class:
def show(in_place_of_self):
print("It is not a keyword "
"and you can use a different keyword")
object = this_is_class()
object.show()

Output:

It is not a keyword and you can use a different keyword
  • Self: Pointer to Current Object

In Python, self is the keyword referring to the current instance of a class. Creating an object from a class is actually constructing a unique object that possesses its attributes and methods. The self inside the class helps link those attributes and methods to a particular created object.

Here’s an example to explain this more clearly:

class Demo:

def __init__(self):
print("Address of self = ", id(self))
obj = Demo()
("Address of object = ", id(obj))
/python]
<b>Output:</b></pre>
<span>Address of self =  140273244381008</span>

<span>Address of object =  140273244381008</span>
<pre style="text-align: justify;"></pre>
<h3><b>Explanation:</b></h3>
<ul>
 	<li aria-level="1"><span>(using </span><span>obj = Demo()</span><span>) is used to instantiate the class Demo, the memory address of </span><span>self</span><span> inside the class is the same as the object </span><span>obj</span><span> created outside. This shows that </span><span>self</span><span> represents the object being created.</span></li>
</ul>
<span>Now, let’s create a more detailed example. This time, we’ll define a class representing as a </span><span>Phone</span><span>, with two attributes like </span><span>brand</span><span> and </span><span>price</span><span>. We will also add a method to show the details.</span>
<pre style="text-align: justify;"></pre>
<span>class Phone:</span>

<b>    </b>

<span>    # init method (constructor) to initialize the brand and price</span>
<pre>[python]
 __init__(self, brand, price):
self.brand = brand
self.price = price

    # method to show the phone details

def show_details(self):
("Brand:", self.brand)
print("Price:", self.price

# Creating objects for two different phones


iphone = Phone("iPhone 13", 999)
samsung = Phone("Samsung Galaxy S21", 850)
/python]</pre>
<span># Calling the show_details method for each object</span>
<pre>[python]
iphone.show_details()  # this is the same as Phone.show_details(iphone)
samsung.show_details() # this is the same as Phone.show_details(samsung)

# Accessing the attributes directly

print("iPhone price is", iphone.price)
print("Samsung brand is", samsung.brand)

Output: Brand: iPhone 13 Price: 999 Brand: Samsung Galaxy S21 Price: 850 iPhone price is 999 Samsung brand is Samsung Galaxy S21

  • Self in Constructors and Methods

self is a special keyword in Python that refers to the instance of the class. self must be the first parameter of both constructor methods (__init__()) and any instance methods of a class.

For a clearer explanation, see this:

  • When creating an object, the constructor, commonly known as the __init__() method, is used to initialize it.
  • Python automatically gives the object itself as the first argument whenever you create an object. For this reason, in the __init__() function and other instance methods, self must be the first parameter.

If you don’t include self, Python will raise an error because it doesn’t know where to put the object reference.

Here’s a revised example to review: 

Example:

class Check:

def __init__(self):  # 'self' is included as the first argument
print("This is the constructor")

# Create an object of the Check class

obj = Check()
print("Worked fine")

In this example:

    • When Check() is invoked, Python automatically passes the object reference (obj) to the self parameter of the __init__() method.

 

    • The code works fine, and “This is the constructor” gets printed.

 

 

  • Is Self a Convention?

In Python, instance methods such as __init__ need to know which particular object they are working on. To be able to do this, a method has a parameter called self, which refers to the current object or instance of the class. You could technically call it anything you want; however, everyone uses self because it clearly shows that the method belongs to an object of the class. Using self also helps with consistency; hence, others-and, in fact, you too-will be less likely to misunderstand your code.

Example using self:

class Dog:
def __init__(self, name):
self.name = name  # 'self' refers to the instance of Dog
(f"The dog's name is {self.name}")
# Creating an object of the Dog class
my_dog = Dog("Buddy")
In this example:
    • self.name refers to the name attribute of the specific object (in this case, my_dog).

 

 

    • When Dog(“Buddy”) is called, Python passes the my_dog instance to self, and the constructor assigns “Buddy” to self.name.

 

 

Example using something other than self:

Technically, you can replace self with another word like obj, but this is not recommended:

class Dog:
def __init__(obj, name):  # Using 'obj' instead of 'self'
obj.name = name
print(f"The dog's name is {obj.name}")
my_dog = Dog("Buddy")
This will work, but it’s confusing. People expect to see self because it's the standard way to refer to the instance of the class.

FAQs

Why is self explicitly defined everytime?

In Python, self is used every time you define it because it helps the method know which object you are actually dealing with. When you call a method on an instance of a class, Python passes that very same instance as the first argument, but you need to define self to catch that. By explicitly including self, you are telling Python: “This method belongs to this particular object.”

Example:

class Car:
def start(self):
print("Car is starting")
my_car = Car()
my_car.start()
  • Here, self refers to the my_car object. When my_car.start() is called, Python passes my_car as self so the method knows which car is starting.

If we didn’t define self, the method wouldn’t know which object it’s referring to.

  • What Happens Internally when we use Self?

When you use self in Python, it’s a way for instance methods—like __init__ or other methods in a class—to refer to the actual object that called the method.

This is what goes on inside you when you tap into your self:

  1. Object creation: When you create an object from a class (e.g., my_car = Car()), Python configures the memory for that object.
  2. Calling a  Method: This also applies to methods, calling the method on the object and passing it as the first argument to that method, then Python takes care of the rest of the objects, such as passing my_car in this example: my_car.start().
  3. Assigning to self: The function takes the object as its self parameter. It can then use this to access the attributes of the object, as well as other methods. Without a self parameter, no function would know which object it has to work on.

Example:

class Car:
def __init__(self, color):
self.color = color  # 'self' refers to the specific car object
def show_color(self):
print(f"The car is {self.color}")  # 'self' accesses the car's color
my_car = Car("red")
my_car.show_color()

What happens internally:

  • Step 1: my_car = Car(“red”) creates a new Car object.
  • Step 2: Python passes the my_car object to self in the __init__ method.
  • Step 3: When my_car.show_color() is called, Python again passes my_car as self, allowing the method to print the color of that specific car.


  • How to avoid self?

You can avoid using self by using @staticmethod or @classmethod decorators in Python. These decorators allow you to create methods that don’t need self because they don’t interact with the instance (object).

Example using @staticmethod (no self needed):

class MathOperations:
@staticmethod
def add(a, b):
return a + b
# Calling the static method without needing an object
result = MathOperations.add(5, 3)
print(result)
Output: 8
  • @staticmethod: The method doesn’t need self because it doesn’t depend on any object’s state.

Example using @classmethod:

class Car:
wheels = 4  # Class attribute
@classmethod
def show_wheels(cls):
return cls.wheels
# Calling the class method without needing an instance
print(Car.show_wheels())  # Output: 4
@classmethod: Instead of self, it uses cls to access class-level attributes, but no specific object is needed.

With this, we have come to the end of our article. I hope you understood the use of self and how it works in Python.

Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible or join our Python Training in Chennai Today..

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 25th January,2025

25th January

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What is the use of self in Python?

edureka.co