What is the variable self in the init method

Although I did not understand most of what Jatin taught in this video but the main doubt is that why is he typing “self.name=name” inside the init method and what is the variable “self”

Hi @Anuvrat99

class A(object):
    def __init__(self):
        self.x = 'Hello'

    def method_a(self, foo):
        print self.x + ' ' + foo

the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in

a = A()               # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument

When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello') ) will also get passed as arguments–in this case causing an exception to be raised, since the __init__ method isn’t expecting them. Setting variables as self.x sets variables as members of the A object (accessible for the lifetime of the object).

Hope this might helps :slightly_smiling_face:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.