In Python, a constructor is a special type of method used for initializing the attributes of a class. Unlike in other Object-Oriented languages where you have to explicitly call the constructor, in Python, a constructor is automatically called when an object is created for a class.
What is a Constructor?
In Python, constructors are defined with the help of the init() method. This method is automatically called when an object of a class is created. It’s also used to initialize the attributes of a class. This method can also take parameters, which can be provided at the time of the creation of the object.
Creating a constructor
Constructors in Python are pretty easy to define. All you need is to define a method within your class with the name init(). This method is invoked whenever an object of the class is constructed.
1 2 3 4 |
class Student: def __init__(self, name, age): self.name = name self.age = age |
Invoking a constructor implicitly
As I already said, in Python you don’t have to call a constructor explicitly. It automatically gets called every time an object is created for a class. Here’s how you do it:
1 |
s1 = Student("John", 25) |
As you can see above, you don’t need to explicitly call the init() method. This is done by Python internally.
Output Attributes of a Constructor
To access the values assigned to the attributes of a class by a constructor, simply create an object for the class and output its name as follows:
1 2 3 |
s1 = Student("John", 25) print(s1.name) print(s1.age) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 |
class Student: def __init__(self, name, age): self.name = name self.age = age s1 = Student("John", 25) s2 = Student("Alice", 23) print(s1.name) print(s1.age) print(s2.name) print(s2.age) |
Output
John 25 Alice 23
Conclusion
In Python, a constructor is a very crucial part of class definitions. They play a significant role in Object-Oriented Programming by initializing the attributes of a class the moment an object is created for it. It’s important to understand that the constructor is not explicitly called. It’s Python’s beauty that it takes care of such invocations internally.