__init__() is a builtin function in Python, that is called whenever an object is created. __init__() initializes the state for the object. Meaning, it is a place where we can set out initial or primary state of our object.
We can also pass arguments to __init__() function, so that each object when created, can be created as unique.
If __init__() function is not defined in a class, there will be an implicit call to the inbuilt __init__() function.
Example 1: __init__() Function
In the following example, we have defined a class with __init__() function, where we will initialize some of the object parameters.
class Laptop: def __init__(self, name, processor, hdd, ram, cost): self.name = name self.processor = processor self.hdd = hdd self.ram = ram self.cost = cost def details(self): print('The details of the laptop are:') print('Name :', self.name) print('Processor :', self.processor) print('HDD Capacity :', self.hdd) print('RAM :', self.ram) print('Cost($) :', self.cost) #create object laptop1 = Laptop('Dell Alienware', 'Intel Core i7', 512, 8, 2500.00) print(laptop1.name) print(laptop1.processor) laptop1.details()
Dell Alienware Intel Core i7 The details of the laptop are: Name : Dell Alienware Processor : Intel Core i7 HDD Capacity : 512 RAM : 8 Cost($) : 2500.0
You can see that we have done lot of things with the class object. We will look deeper into those aspects.
__init__()function initialized parameters, with the values passed as arguments to it.
- The declaration part of parameters, for the class, has been done inside the
- The parameters can be accessed in other methods of the class and also with the object reference.
In this tutorial of Python Examples, we learned how to override inbuilt __init__() function of a Python Class.