__init__ in python
If you have been working with the Object-oriented programming, you might have come across _init_ word quite a few times. __init__ is a Python method. It is similar to the constructors in languages like Java and C++. Knowing classes and objects in Python will make the __init__ method understandable.
Here is some required pre-requisite knowledge:
Here is a simple example of a class and an object:
We created a class named planet. In the class:
Now, we created object earth and accessed the two variables and the method from the class without passing any arguments.
Now, what is self in the class?
When we create an object for the class and call the function, the self is replaced with the created object. It is like a placeholder for the object. In the class we created, we have two variables common to all the objects we create. Hence, even if we called the variables with the object name, we will get the same values for all the objects.
Now, let us understand what '__init__' can do?
Now, let us see the above example with __init__ method:
When we created the object 'earth':
This is the inner mechanism in the __init__ method.
This way, the object earth () can have its attributes.
Now, if we create another object:
Hence, we can create any number of objects, and every object can have its values for the attributes.
This is the functionality of the __init__ method in object-oriented programming in Python.
Let us see one more example:
In the program, we created a class called "Student" with three attributes: name, age and email. Using the self variable, we defined the attributes in the __init__ method. We created two objects, stud and stud2. For both the objects, we already gave the value for email and asked the user for inputs for name and age attributes and then passed the values to the objects.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week