New Python developers who have a knowledge of Java or C++ finds this topic a little bit confusing because constructor in other programming languages has a same name as that of a class but in Python constructor is declared using __init__
method. __init__ is one of the magic methods that is defined inside a class and is called automatically when an instance of a class is created. It is sometimes known as dunder-init. It is used to initialize the instance variables. It takes default, keyworded and non-keyworded variable-length arguments.
There are four different ways of declaring __init__ in Python-
def __init__(self, param1, param2, ..., paramn): statements #__init__ method with default argument def __init__(self, param1='defaultvalue1', param2, ..., paramn): statements #__init__ method with non-keyworded variable-length argument def __init__(self, *args): statements #__init__ method with keyworded variable-length argument def __init__(self, **kwargs): statements
Note:- A class should have atmost one __init__ method. If __init__ is not defined by you in a class then Python Interpreter will generate __init__() method that has an empty body. When you define more than one __init__ inside a class then only the last defined __init__ will be called when you create an object.
It is mandatory to specify self
parameter to __init__
#Student class having __init__ with default argument class Student: def __init__(self, name, standard='sixth'): self.name = name self.standard = standard def display(self): print('Student Name:', self.name) print('Studies in', self.standard) s2 = Student('Geeta Sahu', 'tenth') s1.display() s2 = Student('Mohit Natani') s2.display()
Output
Student Name: Geeta Sahu Studies in tenth Student Name: Mohit Natani Studies in sixth
#Car class having __init__ with default argument class Car: def __init__(self, **kwargs): self.modelName = kwargs['modelName'] self.modelYear = kwargs['modelYear'] def display(self): print('Model Name:', self.modelName) print('Model Year:', self.modelYear) c = Car(modelName='Jaguar F-Type', modelYear=2020) c.display()
Output
Model Name: Jaguar F-Type Model Year: 2020