Many of the students and even programmers gets some confusion about the use of self in python and understand its real meaning. Here comes a solution for it.
The first argument of every class method including init always refers to the current instance of class. If specifically talking about init, self refers to newly created object. In layman language it refers to the object. I will provide an example to show what I mean
class name_class()
def __init__(self,argument1,argument2):
self.argument1= argument1;
self.argument2= argument2;
Now let us create a object of the class.
object1 = class(2,3)..................................................(1{Instance 1})
Self refers to object1. You can understand it as name_class.method(object1, argument1,argument2)
SO self gives reference to the current object
Better Explanation of Self: If you have created different instances of class, how would you distinguish between them in python
Example
object2= class(4,5).....................................(2{instance 2})
IF I would evaluate object1.x, answer would be = 2 whereas object2.x will give me answer as 4.
Format() Method: Returns the formatted string.
For example, taking the same case print(‘first value is {object1.argument1 } and second value is {object1.argument2}’.format(object1=object1)
Watch video Python Self and Python String Format | AI SANGAM online without registration, duration hours minute second in high quality. This video was added by user Al Sangam 04 July 2018, don't forget to share it with your friends and acquaintances, it has been viewed on our site 53 once and liked it 0 people.