No, __init__
is a method (constructor) that sets up the object, while self refers to the object itself.
When working with classes in Python, the concept of self
is fundamental. It allows you to refer to the class instance within its methods, making Python’s approach to object-oriented programming more flexible. Unlike languages like C++ or Java, Python requires the explicit use of self
when defining instance methods, making it a critical part of Python class design.
self
In Python, self
represents the class instance. It acts as a reference to the current object, allowing you to access and modify attributes and call class methods.
Let’s start by looking at a simple Python class that uses self
:
# Define a class called FruitBasketclass FruitBasket:# Constructor: Initializes the fruit list and total countdef __init__(self, fruits, total):self.fruit_list = fruitsself.total = total# Method to display the total costdef show_total(self):print("Total:", self.total)# Method to display the list of fruits in the basketdef show_basket(self):print("Cart:", self.fruit_list)# Method to display both the total and the list of fruitsdef show_bill(self):self.show_total()self.show_basket()# Instance of the FruitBasket class is created with a list of fruits and a total costmy_basket = FruitBasket(["apple", "peach", "orange"], 50)# Call the show_bill method to display the total cost and the list of fruitsmy_basket.show_bill()
In the above code:
self
is used inside the class to access the instance variables fruit_list
and total
.
It is also used to call the methods show_total()
and show_basket()
within the show_bill()
method.
Try it yourself: Modify the __init__
method to accept an expiry
parameter for each fruit. Also add a method to display the expiry information to get a better hands-on experience.
self
explicitly defined every time?In Python, the first argument of any method in a class must be the object itself. self
is not a keyword, but it is the convention used by Python developers. It allows each method to access instance variables and other methods belonging to that instance. While the name self
is a convention, you could use any other name, but sticking to the standard improves code readability.
Let’s understand this with the help of an example. Below is the same code as we have seen above, but here we are using basket
instead of self
.
# Define a class called FruitBasketclass FruitBasket:# Constructor: Initializes fruit_list and total attributes with custom name basket for selfdef __init__(basket, fruits, total):basket.fruit_list = fruitsbasket.total = total# Method to display the total cost of the basketdef show_total(basket):print("Total:", basket.total)# Method to display the list of fruits in the basketdef show_basket(basket):print("Cart:", basket.fruit_list)# Creating an instance of FruitBasket with a list of fruits and a total costmy_basket = FruitBasket(["apple", "peach", "orange"], 50)# Calling the show_total method to display the total costmy_basket.show_total()# Calling the show_basket method to display the list of fruitsmy_basket.show_basket()
This still works, but it’s best to stick with self
because:
Readability: self
is the standard convention, making code easier to understand.
Consistency: It aligns with community practices, ensuring uniformity across projects.
Tool support: Many tools and documentation assume the use of self
.
Avoids confusion: Using anything else may confuse others or obscure code meaning.
In short, it keeps your code clean, consistent, and easily readable.
self
constructorWhen you define a class constructor in Python, self
is used to initialize the instance variables for each object. The __init__()
method is the constructor, and self
must be the first parameter.
Here’s how it looks in a class:
# Define a class called FruitBasketclass FruitBasket:# Constructor: Initializes the fruit_list and total attributesdef __init__(self, fruits, total):self.fruit_list = fruitsself.total = total# Creating an instance of FruitBasket with a list of fruits and a total costmy_basket = FruitBasket(["apple", "peach", "orange"], 50)# Accessing the fruit_list attribute of the instance and printing itprint("Fruits in basket:", my_basket.fruit_list)# Accessing the total attribute of the instance and printing itprint("Total cost:", my_basket.total)
In the above code, we define a class FruitBasket
, initialize it with a list of fruits and a total amount, and create an instance to access these attributes.
Self
in constructors and methodsConstructors and methods inside a class use self
to reference the instance. Without self
, Python has no way of knowing which instance variables or methods should be accessed.
For instance, if you were to omit self
in a method, it will throw an error because the self
argument is missing in the method.
class FruitBasket:def show_total():print("Total:", total) # This will cause an error# Creating an instance (optional, but the error is from the method)# my_basket = FruitBasket()# Uncomment to see the error# my_basket.show_total()
The method show_total
lacks self
, which is necessary to access the instance variables like total
. Without self
, Python doesn’t know which instance’s total
to refer to.
Uncomment lines 7 and 8 to see the change in the output.
self
to a method?Yes, when defining a method inside a class, you must include self
as the first parameter. However, when calling the method from an instance, you do not need to pass self
explicitly. Python does that automatically.
# Define the ExampleClass with a method that assigns a value to an instance attributeclass ExampleClass:def example_method(self, value):self.value = value# Create an instance of ExampleClassexample = ExampleClass()# Call the example_method on the instance and pass 10 as the value to assignexample.example_method(10)# Print the value assigned to the instance attribute 'value'print("Assigned value:", example.value)
In this example, Python automatically passes self
when calling example.example_method(10)
.
self
and init
self
refers to the current instance of the class. It is used to access variables and methods within the class, whereas __init__
is a special method (constructor) that initializes the instance’s attributes when the object is created.
Here’s an example to clarify the difference:
# Define a class called MyClassclass MyClass:# Constructor: Initializes the value attribute of the class instancedef __init__(self, value):self.value = value# Method to display the value of the value attributedef show_value(self):print("Value:", self.value)# Creating an instance of MyClass with the value 10obj = MyClass(10)# Calling the show_value method on the instance to display the value attributeobj.show_value()
Here,
__init__
method is the constructor method that runs when an object is created. It initializes the instance’s attributes, in this case, self.value = value
assigns the input value
to the object’s value
.
self
refers to the current instance of the class. It’s used to access the instance’s variables and methods. In self.value
, the self
ensures the value
belongs to that particular instance.
Key takeaways:
self
in Python: The self keyword in Python represents the instance of the class, enabling access to the class’s variables and methods
__init__
method: A special method (constructor) used to initialize attributes of the class when an object is created.
Custom naming for self
: Although you can use any name instead of self
, it’s best to stick with the convention for better readability and consistency.
Accessing instance attributes: self
allows instance attributes to be accessed and modified across different methods in a class.
Difference between self
and __init__
: self
refers to the object itself, while __init__
is the constructor that sets up the object’s attributes when it’s created.
Become a Python developer with our comprehensive learning path!
Ready to kickstart your career as a Python Developer? Our “Become a Python Developer” path is designed to take you from your first line of code to landing your first job.
This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.
Haven’t found what you were looking for? Contact Us
Free Resources