In Python, Constructor is a special method used for initializing newly created objects. The constructor method is called "__init__()" and it gets automatically invoked when a new object of the class is created.
__init__() method takes the first argument `self` which indicates the current instance of a class. we can also set more parameters to an object while creating a new object, for that, we need to declare more parameters into the function and it will bind to the current object.
The `self` parameter indicates the current instance of the class and accesses the class variables. We can give any name to `self` such as `this` and more, but it needs to be the first parameter of any function that belongs to the class. It allows us to perform any necessary initialization for the object.
Here's a basic example of a constructor method:
Calling the Constructor method when we don't have an attribute to bind with an object while creating an instance of a class. if we don't create a default constructor method in a class, then the Python interpreter automatically creates one for us.
def __init__(self):
Call the Constructor method when we have attributes to bind with an object while creating an instance of a class.
def __init__(self, arg1, arg2): # Initialize instance attributes self.arg1 = arg1 self.arg2 = arg2
class YourClass: # Constructor method def __init__(self, arg1, arg2): # Initialize instance attributes self.arg1 = arg1 self.arg2 = arg2 # Creating an object of YourClass obj = YourClass("argument1", "argument2") # Accessing instance attributes print(obj.arg1) # Output: argument1 print(obj.arg2) # Output: argument2
The "YourClass" has a constructor method "__init__()" which takes three parameters: "self", "arg1", and "arg2".
When an object of "YourClass" is created (obj = YourClass("argument1", "argument2")), the "__init__()" method is automatically called with self-referring to the newly created object, and "arg1" and "arg2" are passed as arguments.
Inside the constructor, "arg1" and "arg2" are assigned to instance attributes "self.arg1" and "self.arg2", respectively.
Later, we can access these instance attributes using dot notation obj.arg1, obj.arg2 to retrieve the values assigned during object creation.
Constructors are commonly used to initialize instance variables, set default values, or perform any other necessary setup when an object is created.
They are essential in ensuring that objects are properly initialized before they are used in the program.