How to Use the Python __init__ Method



In this article, you will learn how to use the Python __init__ method.

Python __init__ Method

The __init__ method is a special method in Python classes that is used to initialize objects. It is called automatically when an object is created, and it can be used to set up any instance variables or perform any other necessary setup actions.

Here is an example of how to use the __init__ method in a Python class:

class Person:
    def __init__(self, name, age): = name
        self.age = age

person1 = Person("Alice", 25)

In this example, we have defined a class called Person. The __init__ method takes two arguments, name and age, which are used to initialize the instance variables and self.age.

We then create an object of the Person class called person1, passing in the arguments “Alice” and 25. This calls the __init__ method and initializes the name and age instance variables for the person1 object.

We can then print out the values of the name and age instance variables using and person1.age.

Overall, the __init__ method is a powerful tool for setting up and initializing objects in Python.