How do I use the 'init' function in Python?

Published on Aug. 22, 2023, 12:16 p.m.

The __init__ function in Python is called the constructor and is used to initialize the attributes of an object when it is created. Here is an example of how to use the __init__ function to define a class with two attributes, name and age:

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

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

In this example, we define a Person class with the __init__ function that takes two arguments, name and age. Inside the constructor, we use the self keyword to create instance variables name and age and set their values based on the arguments passed in.

We then create an instance of the Person class called p1 with the name “Alice” and age 25, and print out the values of name and age.

Output:

Alice
25

Note that the self parameter is a reference to the current instance of the class, and is used to access instance variables and methods. It is always the first parameter of any class method, including the constructor.

Also note that the __init__ function is not required in a class, but it is commonly used to initialize the object’s state when it is created.

Tags:

related content