When Python is used in object oriented way we many at times see self
used as a first parameter. Programmers coming from different languages may find it odd. In this post we are going to look at self
importance in the object oriented world of Python.
Class vs Instance Variables
Let's first look back on class variables and instance variables. Class variables are shared among all the instances of the class and instance variables are kept by respective instances. Therefore instance variable values are different. The class variable values remain same in all instances of class. The instance variables are defined inside a method unlike class variables.
An example will help to understand on how class variables and instance variables differ. Consider a class AddNumbers
which can be used to add two numbers. Class variables are defined just after the class definition and before any methods.Instance variables are defined inside methods.
After defining the class let’s create instances object1
and object2
.Let’s try to access the class variables and instance variables of the two instances. The below example gives us the intuition that the class variables of each instance will have the same value and the instance specific variables will vary according to the values provided in the instances.
Class vs Instance Methods
Just like an instance and class variables, there are instance and class methods. Class methods are used to get or set the class details. Instance methods are used to get or set the instance details. In class methods there is a special parameter cls
which represents the class that should be placed as the first parameter. We will look at cls
some other time.
Let's add an instance method addition to AddNumbers class. At this point many questions wander us. why are we using self as first parameter? why are we not passing any paramter when method is called? We will be able to get all answers in the following sections.
True 'Self'
Self
helps the Python interpreter in identifying which object instance to apply the method invocation to. The self argument helps to identify which object instance’s data to work on. When an instance method is invoked, Python arranges for
the first argument to be the invoking object instance, which is always assigned to each method’s self argument. This fact alone explains why self is important
The following steps are self intuitive.
- Create an instance
- Python interpreter converts the instance created (__init__ is called)
- __init__method is provided with the instance and parameter values.
- Call the instance method (addition)
- Python interpreter converts
- addition method is provided with the instance.
Self is not a Keyword. It is a coding convention.
If you have any question or feedback, please do reach out to me by commenting below.