Data Science and Machine Learning Internship ...
- 22k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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()
Fruit is apple color is red Fruit is grapes color is green
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.
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
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 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:
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:
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:
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.
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:
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.
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.”
class Car: def start(self): print("Car is starting") my_car = Car() my_car.start()
If we didn’t define self, the method wouldn’t know which object it’s referring to.
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:
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()
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).
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
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..
Course Name | Date | Details |
---|---|---|
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 |
edureka.co