__ init __ in PythonIf you have been using object-oriented programming, you may have run into the word "init" quite often. __init__ is a Python method. It is analogous to the constructors in languages like Java and C++. Knowing classes and objects in Python will make the __init__ method understandable. Some Rpre-requisite Knowledge:
Here is a simple example of a class and an object: Output Planet Solar system I'm earth I'm a planet in Solar system AnalysisA class called Planet was made. During class:
After creating the object Earth, we used the class's two variables and method without supplying any inputs.
Now, what is self in the class?The self is substituted with the newly produced object when the function is called after creating an object for the class. It functions as the object's kind of placeholder. All the objects we generate share two variables in the class we constructed. Therefore, even if we called the variables by the names of the objects, we would still receive the same results. Let's now examine what '__init__' is capable of.
Let's look at the example from above using the __init__ method now:Output I am earth I am the 3 planet in the solar system Understanding:
When the object "earth" was created: This is the __init__ method's internal workings. The planet Earth () can have its characteristics in this fashion. If we make another item now: Output I am earth I am the 3 planet in the solar system I am venus I am the 2 planet in the solar system As a result, we can build an unlimited number of objects, each with a unique set of attribute values. The __init__ method in Python's object-oriented programming has these capabilities. Let's look at one more instance:
Output Please enter the name of the student1: Jeevani Please enter the age of the student1: 19 Please enter the name of the student2: Harini Please enter the age of the student2: 15 Stud_1.name = Jeevani Stud_2.name = Harini Understanding:We established a class called "Student" with the following three properties in the program: name, age, and email. We defined the attributes using the self-variable in the __init__ method. Two objects?stud and stud2?were produced. We already provided the email attribute value for both objects and requested the user's input for the name and age attributes before passing the values to the objects. Note:
Next Topic__dict__ in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India