less than 1 minute read

The self parameter is a reference to the current instance of the class, is always pointing to current Object and is used to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like but it has to be the first parameter of any function in the class. It is advisable to use self as name because it increases the readability of code, and it is also a good programming practice.

Example-1:

class food():
# init method or constructor
    def __init__(self, fruit, color):
        self.fruit = fruit
        self.color = color
 
    def show(self):
        print("The fruit is", self.fruit + " the color is", self.color)

# creating instances     
apple = food("apple", "red")
grapes = food("banana", "yellow")
 
apple.show()
grapes.show()

Example-2:

# class
class Laptop:
   # init method
   def __init__(self, company, model):
      # self
      self.company = company
      self.model = model
# creating instances for the class Laptop
laptop_one = Laptop('Lenovo', '#34578')
laptop_two = Laptop('Dell', '#9600')
# printing the properties of the instances
print("Laptop One: ", laptop_one.company + " - " + laptop_one.model)
print("Laptop Two:" ,laptop_two.company + " - " + laptop_two.model)

References

Self definition

Self in python class

Example