What is the function of “self”?

Technology CommunityCategory: PythonWhat is the function of “self”?
VietMX Staff asked 3 years ago

Self is a variable that represents the instance of the object to itself. In most of the object oriented programming language, this is passed to the methods as a hidden parameters that is defined by an object. But, in python, it is declared and passed explicitly. It is the first argument that gets created in the instance of the class A and the parameters to the methods are passed automatically. It refers to separate instance of the variable for individual objects.

Let’s say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2): #do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.