search

What is the "self" keyword in Python?

In Python, the self keyword is a convention used to refer to the instance of a class within its own methods. It acts as a reference to the current object on which a method is being called. The use of self helps differentiate between the instance variables of a class and local variables or parameters within a method.

When defining a method in a class, the first parameter is typically named self, although you can choose any valid variable name. This parameter represents the instance of the class and allows you to access its attributes and methods.

Here's an example to illustrate the use of self:

class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def start_engine(self):
        print("Starting the engine of the", self.color, self.brand, "car.")

    def change_color(self, new_color):
        self.color = new_color
        print("The car's color has been changed to", self.color)


# Creating an instance of the Car class
my_car = Car("Toyota", "Blue")

# Accessing instance variables using self
print(my_car.brand)  # Output: Toyota
print(my_car.color)  # Output: Blue

# Calling methods using self
my_car.start_engine()  # Output: Starting the engine of the Blue Toyota car.
my_car.change_color("Red")  # Output: The car's color has been changed to Red

In the above example, the self parameter is used within the methods of the Car class. The self.brand and self.color statements inside the __init__ method are used to assign values to the instance variables of the class. Similarly, the self.color and self.brand expressions within the start_engine method and the change_color method access the instance variables of the object on which the methods are called.

By convention, self is the recommended name for the first parameter of instance methods in Python classes. However, it is not a reserved keyword and can technically be replaced with any valid variable name. It is important to maintain consistency and follow the convention to ensure code readability and maintainability.

Related Questions You Might Be Interested