Understanding self in Python

Ashan Priyadarshana
Quick Code
Published in
5 min readFeb 4, 2018

python self — intuition

Once you start using Python, there is no escaping from this word “self”. It is seen in method definitions and in variable initialization. But getting the idea behind it seems somewhat troublesome. Hopefully, at the end of this, you will get an intuitive idea of what “self” is and where you should use it.

But before talking about the self keyword (which is actually not a python keyword or any special literal), first, let’s recall what are class variables and instance variables. Class variables are variables that are being shared with all instances (objects) which were created using that particular class. So when accessed a class variable from any instance, the value will be the same. Instance variables, on the other hand, are variables which all instances keep for themselves (i.e a particular object owns its instance variables). So typically values of instance variables differ from instance to instance.

Class variables in python are defined just after the class definition and outside of any methods:

class SomeClass:
variable_1 = “ This is a class variable”
variable_2 = 100 #this is also a class variable

Unlike class variables, instance variables should be defined within methods:

class SomeClass:
variable_1 = “ This is a class variable”
variable_2 = 100 #this is also a class variable.

def __init__(self, param1, param2):
self.instance_var1 = param1
#instance_var1 is a instance variable
self.instance_var2 = param2
#instance_var2 is a instance variable

Let’s instantiate above class and do some introspections about those instances and above class:

>>> obj1 = SomeClass("some thing", 18) 
#creating instance of SomeClass named obj1
>>> obj2 = SomeClass(28, 6)
#creating a instance of SomeClass named obj2

>>> obj1.variable_1
'a class variable'

>>> obj2.variable_1
'a class variable'

So as seen above, both obj1 and obj2 gives the same value when variable_1 is accessed, which is the normal behavior that we should expect from a class variable. Let’s find about instance variables:

>>> obj1.instance_var1
'some thing'
>>> obj2.instance_var1

Ashan Priyadarshana
Quick Code

Associate Technical Lead | BSc. Information Technology | MSc. Artificial Intelligence | Founder Programming.lk | GSoC 2017 |