What is init in python

王林
Release: 2023-08-31 09:41:05
forward
1195 people have browsed it

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.

Create a class with __init__() method

Example

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)
Copy after login

Output

Student Name =  David
Student Rank =  2
Student Points =  90
Copy after login

Create a class with __init__() and custom methods

Example

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()
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!