How to Use the Python __init__ Method

09/17/2021

Contents

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):
        self.name = name
        self.age = age

person1 = Person("Alice", 25)
print(person1.name)
print(person1.age)

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 self.name 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 person1.name and person1.age.

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