In Python, init is a special method also known as a constructor. It is automatically called whenever a new object is created from a class. This method helps in initializing the attributes of the class whenever an object is instantiated. This tutorial will show you how to call the init method in Python.
Step 1: Define a Class with an __init__ Method
First, let’s create a simple class with an init method. In this example, we will create a class named Person with the attributes name and age:
1 2 3 4 |
class Person: def __init__(self, name, age): self.name = name self.age = age |
As you can see, the init method takes two parameters: name and age. The parameters are preceded by the self
keyword, which refers to the instance of the class itself.
Step 2: Instantiate an Object from the Class
Now that the class is defined, let’s create an object of the class. In this case, we create a new Person object called person1:
1 |
person1 = Person("Alice", 30) |
By passing the name and age arguments during the instantiation, the init method initializes the properties of the object. In this case, person1 is now a Person object with name set to “Alice” and age set to 30.
Step 3: Access the Object’s Attributes
After calling the init method and initializing the attributes, you can access the object’s attributes using the dot (.) notation:
1 2 |
print(person1.name) print(person1.age) |
This code will output the following:
Alice 30
Step 4: Updating the Object’s Attributes
If you want to update the object’s attributes, you can do so by simply assigning a new value to the attribute.
1 2 |
person1.name = "Bob" print(person1.name) |
The output will now be:
Bob
Full Code Example
Here’s the full code sample based on the steps provided above:
1 2 3 4 5 6 7 8 9 10 11 12 |
class Person: def __init__(self, name, age): self.name = name self.age = age person1 = Person("Alice", 30) print(person1.name) print(person1.age) person1.name = "Bob" print(person1.name) |
This code will output the following:
Alice 30 Bob
Conclusion
In this tutorial, we covered how to call the init method in Python. By following these steps, you can now create classes with an init method that initializes the object’s attributes during instantiation, and access or update these attributes as needed. Remember that utilizing the init method properly ensures better organization and initialization of your classes in Python.