w3resource

Explain the purpose of the self parameter in Python class methods.

Python Class Methods and the 'self' Parameter

The 'self' parameter in Python class methods represents the class instance (object). Methods can access and manipulate attributes (variables) and call other methods of the same class using this special variable.

When you define a method in a class, you need to include the 'self' parameter as the first parameter of the method. This is a convention in Python, though you can name it differently; using 'self' is a widely accepted practice and makes the code more readable.

Here's an example of the 'self' parameter:

class Motorbike:
    def __init__(self, make, model):
        self.make = make
        self.model = model
        self.speed = 0
    def accelerate(self, speed_increase):
        self.speed += speed_increase
    def brake(self, speed_decrease):
        self.speed -= speed_decrease
    def get_speed(self):
        return self.speed

In the above example, we defined a class "Motorbike" with methods 'accelerate', 'brake', and 'get_speed'. The 'self' parameter allows these methods to access the instance attributes 'make', 'model', and 'speed', as well as modify the 'speed' attribute based on the input provided to the methods.

When you create an object (instance) of the "Motorbike" class and call its methods, the 'self' parameter is automatically passed in by Python.

Example:


my_motorbike = Motorbike("FAREAST", "DF250RTS")
my_motorbike.accelerate(40)  # Increase speed by 40
print(my_motorbike.get_speed())  # Output:40
my_motorbike.brake(10)  # Decrease speed by 10
print(my_motorbike.get_speed())  # Output: 30


Follow us on Facebook and Twitter for latest update.