7. Understanding the self variable

Let's understand in detail what self variable means.

In a class definition, the signature of __init__ method is as shown below:

class Class_Name:

	def __init__(self, arg1,..,argN):
		self.arg1 = arg1
		...
		self.argN = argN
	
	def method1(self, arg1,...,argN)
	
	def method2(self, arg1,...,argN)

 

  • We have to explicitly declare the first argument of every class method including the __init__ method as self . By convention, this argument is always named as self. (Note: self is not a keyword in Python)
  • The other arguments follow after the self and they are initialised by adding themselves to self using dot (.) notation in the __init__ method body.
  • Using self argument, you can access the attributes and methods of the class. It binds the attributes with the given arguments.
  • The self always refers to the current instance of the class.
  • In the init method, self refers to the newly created object and in other class methods, it refers to the object whose method was called.