Home > Article > Backend Development > What is init in python
Classes in Python have an __init__() function. This function is executed when the class is initialized. Let’s take a look at some key points of __init__ -
Classes in Python have an __init__() function.
Similar to the constructor in Java, the __init__() function is executed when the object is created.
__init__() function will be called automatically.
It is used to assign values to the properties of objects.
__init__() method can have flexible parameters. To do this, the arguments passed to the class instantiation operator are passed to __init__().
When a class defines an __init__() method, the instantiation of the class will automatically call the __init__() method to create a new class instance.
Let’s create a class using __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)
Student Name = David Student Rank = 2 Student Points = 90
We will create a class with __init__() here and we will also create and call a custom function -
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()
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
The above is the detailed content of What is init in python. For more information, please follow other related articles on the PHP Chinese website!