What is _init_ in Python?


The classes in Python have the __init__() function. This function gets executed when the class is being initiated. Let’s see some key points bout __init__ -

  • The classes in Python have __init__() function.

  • Similar to constructors in Java, the __init__() function executes when the object gets created.

  • The __init__() function is called automatically.

  • It is used to assign values to the properties of an object.

  • The __init__() method may have arguments for flexibility. For that, the arguments given to the class instantiation operator are passed on to __init__().

  • When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly created class instance.

Create a class with __init__() method

Example

Let us create a class using the __init__() -

class Student: def __init__(self, name, rank, points): self.name = name self.rank = rank self.points = points # Creating an object st = Student("David", 2, 90) print("Student Name = ",st.name) print("Student Rank = ",st.rank) print("Student Points = ",st.points)

Output

Student Name =  David
Student Rank =  2
Student Points =  90

Create a class with __init__() and custom method

Example

We will here create a class with __init__() and a custom function will also be created and called -

class Students: def __init__(self, name, rank, points): self.name = name self.rank = rank self.points = points # custom function def demofunc(self): print("I am "+self.name) print("I got Rank ",+self.rank) # create 4 objects st1 = Students("Steve", 1, 100) st2 = Students("Chris", 2, 90) st3 = Students("Mark", 3, 76) st4 = Students("Kate", 4, 60) # call the functions using the objects created above st1.demofunc() st2.demofunc() st3.demofunc() st4.demofunc()

Output

I am Steve
I got Rank  1
I am Chris
I got Rank  2
I am Mark
I got Rank  3
I am Kate
I got Rank  4

Updated on: 15-Sep-2022

933 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements