Python __init__() - Working and Examples
Python init()
__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 the attributes of an 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.
Simple Example for __init__() in Python
In the following example, we have defined a class with __init__() function, where we will initialize some of the object parameters.
Python Program
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()
Output
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
__init__()
function. - The parameters can be accessed in other methods of the class and also with the object reference.
Summary
In this tutorial of Python Examples, we learned about __init__, how to use __init__ in a class definition, and how to override inbuilt __init__() function of a class in Python.