__init__() Method

Object-oriented programming (OOP) is a paradigm in Python that is based on the concept of “objects”. In OOP, objects have attributes and behaviors encoded as methods. One pivotal method in Python is the __init__() method.

What is init()?

The __init__() method is a special method that Python runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. It’s often referred to as a constructor because it’s used to set initial values for object attributes or other startup procedures.

Here’s a simple example:

1class Car:
2    def __init__(self, color, model):
3        self.color = color
4        self.model = model

In this example, color and model are parameters that the __init__() method takes. Now, when we create a new Car object, we can provide these values.

Let’s create a Car object:

1my_car = Car("Red", "Sedan")
2print(f'My car is a {my_car.color} {my_car.model}.')

Upon running this code, you’d get My car is a Red Sedan.

When the Car object my_car was created, the __init__() method was called with the arguments “Red” and “Sedan”. In the __init__() method, self refers to the newly created object.

Note

In the __init__ method, self refers to the object that triggers the method. It can be named anything you like, but it’s a standard practice to call it self.

If a class doesn’t have an __init__() method, Python will look in its parent class for it. If it doesn’t find one in the parent class either, then it will not throw an error and continue without setting any initial values.

Conclusion

The __init__() method in Python is a powerful feature of object-oriented programming. It allows us to set initial attributes for an object upon its creation. Remember to always include self in the __init__() implementation, as it is the reference to the newly created object.