Self in Python is a reference to the current instance of the class itself (i.e. object created from the class). In Python, every object has an address.
When we create an instance of a class, memory is allocated and data attributes associated with object are initialized. Python uses self keyword internally to refer to the current instance of a class.
This keyword is the first argument (i.e. parameter) of any instance function defined within a class. Whenever we call an instance method using the object reference variable, the object itself is passed as the first parameter.
For this reason, the first parameter of any instance function in the class must be the object itself (i.e. the current instance of class), which is conventionally called “self”. It does not have to be named self, you can call it whatever you like. But, it must be the first argument of any method defined inside a class.
We use it inside the instance method to access data attributes stored in the object. In other words, we can use it to access instance variables that belong to specific to an individual object created from the class.
Self parameter helps in distinguishing between instance variables and local variables within instance methods because without self keyword, a variable will be considered as a local variable inside the method.
Self in Python Constructor and Method
A function called __init__() is used to define a constructor in Python, which takes “self” as the first argument. This method is automatically called when we create an instance of the class.
We use the constructor method to initialize the data attributes of an object when it’s constructed. “Self” plays an important role in the class constructor by allowing us to set the initial values of instance variables. Look at the below figure.
When we define any method inside a class, it is called instance method that takes self as the first parameter. The self parameter allows the instance method to access and manipulate data attributes that are unique to that specific object.
For example, consider a class representing a car. By using “self” keyword, we can modify properties like speed, color, and model for each individual car object. Let’s take some examples based on it.
Example 1:
# Python program to set the initial values of instance variables inside the class. class Student: # Definition of __init__() method with the first parameter self and other parameters. def __init__(self, name, age, grade): # Variables initialization. self.name = name # instance variable. self.age = age # instance variable. self.grade = grade # instance variable. # Instance method definition. def introduce(self): return f"Hi, I'm {self.name}, and I'm {self.age} years old." # Accessing instance variables. # Outside the class definition. # Creating instances of the Student class student1 = Student("Mahika", 18, "A") student2 = Student("Mahi", 17, "B") print(student1.introduce()) # Accessing the instance method. print(student1.grade) # Accessing the instance variable.
Output: Hi, I'm Mahika, and I'm 18 years old. A Hi, I'm Mahi, and I'm 17 years old. B
In this example, we have defined a class named Student. This class contains __init__() constructor method that initializes the instance variables name, age, and grade using the values passed when creating the instances (student1 and student2) of the class.
The use of “self” allows each instance to have its own set of data attributes. The introduce() method defined inside the class uses these data attributes and print the introduction of each student with their respective details on the console.
Outside the class definition, we have created two instances of the class by passing different argument values to its __init__() method. Then, we have called the introduce() method and grade variable using object reference variable student1.
Example 2:
# Python program to create a simple calculator. # Create a class Calcy for calculator. class Calcy: # __init__() constructor method definition def __init__(self, x, y): # Variables initialization. self.x = x # instance variable self.y = y # instance variable # Create a function for addition. def sum(self): z = self.x + self.y print("Addition: ", z) # Create a function for subtraction. def sub(self): z = self.x - self.y print("Subtraction: ", z) # Create a function for multiplication. def multiply(self): z = self.x * self.y print("Multiplication: ", z) # Create a function for division. def div(self): z = self.x / self.y print("Division: ", z) # Outside the class definition. # Create an object of class Calcy. c = Calcy(50, 10) # Call the functions in sequence using reference variable c. c.sum() c.sub() c.multiply() c.div()
Output: Addition: 60 Subtraction: 40 Multiplication: 500 Division: 5.0
In this example, we have created a class Calcy that contains a constructor __init__(), and four instance methods with self parameter. As we create an instance of the class by passing argument values, then the constructor method automatically gets called. Then, the constructor method initializes variables x and y, respectively.
After initialization, we have used it in the four functions, such as sum(), sub(), multiply(), and div(). We have called all the functions in sequence using the object reference variable c outside the class definition.
Accessing Class Method using Self Keyword in Python
When we define a method using @classmethod decorator inside the class, it is called class method or function. This method is bound to the class and not the instance of the class. It operates on the class itself rather than on objects of the class.
In Python, we can access the class method using the self keyword within an instance method. Although it’s more common to call class methods using the class name itself. But there are scenarios where accessing a class method using self might be useful.
Let’s take an example program in which we will access a class method using self keyword.
Example 3:
# Python program to access class method using self. # Create a class MyClass. class MyClass: @classmethod def class_method(cls): print("This is a class method") # Instance method definition. def access_class_method(self): self.class_method() # Accessing class method using self # Creating an instance of the class instance = MyClass() # Calling the method to access the class method instance.access_class_method()
Output: This is a class method
In this example, we have used self keyword to call and access the class method class_method() from within an instance method access_class_method(). The output will display the message defined within the class method.
However, please note that accessing a class method using self might lead to confusion and is generally not the recommended approach. In general, we call the class methods using the class name itself (e.g., MyClass.class_method()).
Using self to access class methods might make your code less readable and harder to understand, so it’s better to follow the conventional practice of calling class methods using the class name.
Accessing Class Variable using Self
When we define any variable inside a class, it is called class variable. It is shared among all instances of a class. It stores data that is common to all objects created from the class. Any changes to class variables are also reflected in all instances.
We can access a class variable using the self keyword within an instance method of the class. Although class variables are typically accessed using the class name itself.
But it is also possible to access them within instance methods using self keyword and can be useful in certain scenarios. Let’s take an example program in which we will access class variables using self and class name.
Example 4:
# Python program to access a class variable using self. # Create a class MyClass. class MyClass: class_variable = "I am a class variable" # Class variable def access_class_variable(self): print(self.class_variable) # Accessing class variable using self # Creating an instance of the class instance = MyClass() # Calling the method to access the class variable instance.access_class_variable()
Output: I am a class variable
In this example, the access_class_variable method uses self.class_variable to access the class variable class_variable from within an instance method. The output will show the value of the class variable.
Remember that accessing class variables using self is possible. However, it’s more common and clearer to access class variables directly using the class name (e.g., MyClass.class_variable). Using self keyword for instance variables and the class name for class variables helps maintain clarity and readability in our code.
Best Practices for Using “Self” in Python
There are the following key points about self in Python that you should keep in mind while using. They are as:
- Always use “self” as the first argument in instance methods.
- Keep the name “self” consistent across all methods to maintain clarity.
- Use meaningful names for the instance variables to enhance code readability.
- Avoid using “self” in class methods (methods decorated with @classmethod) as they don’t deal with instance-specific attributes.
- Do not use the self keyword outside of class definitions.
Can We Use Self in Class Methods in Python?
No, we cannot use the “self” in a class method. We use “cls” parameter in a class method that refers to the class itself. Let’s take a simple example on it.
Example 5:
class MyClass: class_variable = "I am a class variable" # Class variable # Definition of instance methods. def __init__(self, instance_variable): self.instance_variable = instance_variable # Instance variable def instance_method(self): print("This is an instance method") print("Instance variable:", self.instance_variable) # Accessing instance variable. print("Class variable:", self.class_variable) # Definition of class method. @classmethod def class_method(cls): print("This is a class method") print("Class variable:", cls.class_variable) # Accessing class variable. # Creating an instance of the class instance = MyClass("Instance Value") # Calling instance method instance.instance_method() # Calling class method MyClass.class_method()
Output: This is an instance method Instance variable: Instance Value Class variable: I am a class variable This is a class method Class variable: I am a class variable
In this example, we have defined an instance method in which we have used the parameter self to access both the instance variable (instance_variable) and the class variable (class_variable). In addition to it, we have also defined a class method in which we have used the parameter cls to access the class variable (class_variable).
Remember that the parameter “self” is used in instance methods to refer to the instance itself, while the parameter “cls” is used in class methods to refer to the class itself. This difference allows us to work with both instance-specific and class-level data effectively.
In this tutorial, we have explained self keyword in Python with some important example programs that you should practice them. Hope that you will have understood the basic concept of using self and practiced all programs.
Thanks for reading!!!