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…

--

--

Ashan Priyadarshana
Quick Code

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