/  Technology   /  What is the purpose of the word ‘self’ in Python?
What is the purpose of the word 'self' in Python?

What is the purpose of the word ‘self’ in Python?

 

self represents the instance of a class. Using this, we can access the attributes and methods of this class. self always points to the current object so the address of self and the current object is always the same. 

 

Example:

class A:
   def__init__(self):
      print("Address of self is = ",id9self))

a = A()
print("Address of class object a is = ",id(a))

Output:

 

We have taken a class A and defined an __init__() method and just passed self as the parameter and printed the address of self. Then we created an object for this class A, ‘a’, and printed the address of this object found using id().

 

In the code below, we have taken an example of a class Student which has a constructor and a method show() for displaying student details.

 

We have created two separate objects for the same class Student obj1 and obj2 and using these we called the class method show(). self allows each object to have its own attributes and methods and it’ll help us access these. 

 

Note that we can call a class method using the objects in two ways,

  • object_name.class_method() 
  • class_name.class_method(object_name)

 

Example:

class Student ():

   def__init__(self, name, number):
      self.name = name
      self.number = number

   def show(self):
      print("Student name is", self.name )
      print("Student id is", self.number )


obj = Student("Harry", "01")
obj = Student("Oliver", "02")

obj1.show()
Student.show(obj1)
obj2.show()

Output:

 

self must be the first argument to be passed in an instance method and a constructor. If we don’t it raises an error. 

 

Example:

class A:
def__init__(self):
print("Address of self is = ",id9self))

a = A()
print("Address of class object a is = ",id(a))

Output:

 

Note that self is a parameter and not a keyword. It’s mandatory to pass an argument for any instance method, it should not necessarily be self, we can give any other name. But it’s a good practice to use self as it increases the readability of the code.

 

Leave a comment