The __init__() function is a reserved function in python for classes. It allows us to initialize an object’s variables such that they can be set at initialization by input values, rather than fixed values in the class itself.
The syntax isn’t very complex. It’s like any other class method…
def __init__(self, attr1, attr2, attr3, ...): # do whatever with those inputs
We can use the inputs passed into the __init__ to set values to attributes of the object. For example…
class Car: def __init__(self, type, year, miles): self.type = type self.year = year self.mileage = miles drive(self): self.mileage = self.mileage + 5
In this example, we set all the attributes of each object of the Car class, at initialization using the __init__() method. Now, you must be wondering, how do I give these input values when I instantiate the object. It’s easy! Remember the parentheses we used when creating (i.e. instantiating) objects? We put all the arguments that go into the __init__() method between those parentheses, in the same order they are listed in the class definition. Like so…
class Car: def __init__(self, type, year, miles): self.type = type self.year = year self.mileage = miles def drive(self): self.mileage = self.mileage + 5 mercE330 = Car(“coupe”, 2005, 50000) beem5 = Car(“sedan”, 2019, 2000) print(“Merc E 330 is a “ + mercE330.type) print(“Beem 5 Series is a “ + beem5.type)
Merc E 330 is a coupe Beem 5 Series is a sedan
Here, thanks to the __init__() method, we don’t need to go in and edit the attributes of each object (car) of the Car class, instead, each car gets its own unique attributes right when it's created and doesn’t have its attributes set to default values. It truly makes Objects a lot easier to work with in Python. In languages like Java, such a method is comparable to a constructor, although, it is technically not a constructor.