the self variable in python

What is the purpose of self?


Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self

.

The Object is passed into the self parameter so that the object can keep hold of its own data.Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.




See the illustration below:


you can also pass an object instead of self:


see the illustration below:

case1: if you didn't use self in a method in class




class test:
 def print1(name):
  print('name = ',name)
a=test()
a.print1('kay')

output: AttributeError: 'test' object has no attribute 'name'


case 2: when you use self


class test:
 def print1(self,name):
  print('name = ',name)
 a=test()
 a.print1('kay')

case 3:when you use directly the currently following object instead of self


class test:
 def print1(a,name):      #here instead of self we have passedthe currently following object
  print('name = ',name)
a=test()
a.print1('kay')

Comments