Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm learning the Python programming language and I've come across something I don't fully understand.

In a method like:

def method(self, blah):

def __init__(?): 

.... ....

What does self do? What is it meant to be? Is it mandatory?

What does the __init__ method do? Why is it necessary? (etc.)

I think they might be OOP constructs, but I don't know very much.

1 Answer

0 votes
by (106k points)
edited by

__init__ method():-

It is known as a constructor in the object-oriented concepts. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class.

self:-

self is used to represent the instance of the class. With using the “self” keyword we can access the attributes and methods of the class in python.

  • Now let us understand these using an example:-

class Point:

    def __init__(self, x, y): 

       self._x = x 

       self._y = y

Here the __init__ method gets called when memory for the object is allocated:

x = Point(1,2)

If you want to persist the value with the object, it is important to use the self parameter inside an object's method. You implement the __init__ method like this  for instance :

class Point: 

   def __init__(self, x, y): 

     self._x = x 

     self._y = y

To know more about this you can have a look at the following video tutorial:-

Be a Python Expert. Enroll in Python Programming Course by Intellipaat

Related questions

+2 votes
2 answers
asked May 28, 2019 in Python by Nigam (4k points)
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
+1 vote
2 answers

Browse Categories

...