In Python or any other programming languages like C++ or Java, a constructor is a special method which we use it to initialize (assigning values to) the instance members of the class. We also call it as a class constructor in Python.
Python provides a special method __init__() that acts as a class constructor. The name of this special method starts and ends with double underscores.
In Python, the constructor __init__() is a function but actually, it is a method, not a function, because we define it within a class. Hence, the __init__() function acts as a constructor in the class which is used to assign values to the instance members of the class.
This function is the most commonly used in Python. Whenever we create an instance or object of the class in Python, it will automatically search for the __init__() function (i.e. constructor) and execute it.
In simple words, the constructor method will automatically execute whenever we create an instance of the class in the memory. This method is also called initializer method because it initializes the data attributes of an object or class variables.
Therefore, we do not need to call it explicitly. We just have to define it in the class. This method takes at least one argument “self” to identify each object being created.
Syntax of a Constructor in Python
The basic syntax to define a constructor in Python class is as follows:
class ClassName: def __init__(self, parameters): # Constructor body.
In the above syntax, the self parameter refers to the current instance of the class. It is automatically passed by Python when the constructor is invoked.
Constructors can also have parameters just like regular functions in Python. These parameters are used to initialize the object’s attributes. The self parameter refers to the current instance itself, allowing us to access and modify its attributes.
Types of Constructor in Python
There are three types of constructors in Python or other programming languages like Java. They are as:
- Default constructor
- Non-parameterized constructor
- Parameterized constructor
Let’s understand them one by one with the help of examples.
Default Constructor in Python
A constructor that does not have any parameter is called default constructor in Python. When we do not define a constructor inside the class, Python automatically adds a default constructor for that class that does not do anything.
This constructor doesn’t perform any additional initialization beyond creating the object. We cannot pass any argument to default constructor. That’s why it is also known as a no-argument constructor in Python.
Every class must contain a constructor, even if it simply depends on the default constructor. Let us take some examples based on it.
# Python program based on the default constructor. # Class creation. class Employee: emp_name = "John" emp_id = 12345 # Declare a function that accepts an argument self. def display(self): print("Name: ", self.emp_name) print("Id: ", self.emp_id) # Outside the class definition. # Create an object of the class Employee. emp = Employee() # Call the function. emp.display()
Output: Name: John Id: 12345
In this example, we have defined a class Employee, which does not contain any constructor. So, Python implicitly provides a default constructor for that class. This constructor will not do anything in addition to the object creation.
Inside the class, we have defined two class variables: emp_name and emp_id. We have assigned values – “John” and 12345 to these variables, respectively. Class variables (or class attributes) are shared among all instances of the class.
The class also contains a method named display which takes an argument self. In Python, “self” refers to the current instance of the class. The method’s purpose is to display the employee’s name and ID.
Outside the class definition, we have created an object of the Employee class. The default constructor is automatically called when an object is created and doesn’t take any explicit arguments.
At last, we have called the display() method using the reference variable emp, as in the above code. This method call displays the name and ID of the employee based on the values stored in the class attributes.
Non-parameterized Constructor in Python
A constructor which has no parameters in the parentheses except “self” as an argument is called non-parameterized constructor in Python. This constructor does not accept any argument. Therefore, we also call it as a no-argument constructor. There can have statements inside the block of constructor.
Using non-parameterized constructor, we can initialize any values for the instance variables inside the constructor block. Let’s take some example programs based on the non-parameterized constructor.
# Python program based on the non-parameterized constructor. # Class creation. class Test: # Declare non-parameterized constructor. def __init__(self): print("Non-parameterized constructor") # Declare a function with a parameter x. Here, x is a local variable. def display(self, x): print("Python ", x) # Create an object of the class Test. t = Test() # Call the function by passing a string value. t.display("Programming")
Output: Non-parameterized constructor Python Programming
# Python program based on the non-parameterized constructor. # Class creation. class Student: # Non-parameterized constructor. def __init__(self): # Initializing the value of variables. self.st_name = "John" self.st_rollNo = 10 # Declare a function. def display(self): print("Name: ", self.st_name) print("Roll no: ", self.st_rollNo) # Outside the class definition. # Create an object of the class Student. st = Student() # Call the function by passing a string value. st.display()
Output: Name: John Roll no: 10
In this example, we have defined a class named Student. This class contains a constructor method __init__() which automatically gets called when an object of the Student class is created. The self parameter refers to the current instance of the class that is being created.
Inside the constructor, we have defined two instance variables: st_name and st_rollNo. The st_name and st_rollNo instance variables are initialized with a string value “John”, and an integer value 10, respectively.
The statement self.st_name = “John” is setting the value of the instance variable st_name for the current object (instance) of the class. In other words, self.st_name = “John” means that we are assigning the value “John” to the attribute st_name of the current object.
The class also contains a method named display. This method is used to display the attributes of the student object. It will print the name and roll number of the student when the function will be called.
Outside the class definition, we have created an instance of the class Student. The __init__() method is automatically called during object creation.
At last, we have called the display() function using reference variable st. This method call displays the name and roll number of the student based on the values stored in the object’s attributes.
Parameterized Constructor in Python
A constructor that takes one or more parameters along with self argument is called parameterized constructor in Python. We use the parameterized constructor to provide different values to distinct object’s attributes.
In other words, it allows us to initialize instance variables with unlike values. In the case of the non-parameterized constructor, values remain the identical for all objects. An example of parameterized constructor is as follows:
def Person(self, name, age): # Constructor code.
To call the parameterized constructor, we will have to pass arguments while creating the object. Therefore, this constructor is also called argument constructor.
The argument can be of any type, like integer, float, string, character, or object. It can take any number of arguments at the time of creating the class object, depending upon the __init__() function definition.
Python does not put any parameterized constructor by default inside the class. Let’s take some example program based on the parameterized constructor in Python.
# Python program based on the parameterized constructor. class Test: # Declaring a parameterized constructor. def __init__(self, arg): print("Parameterized constructor") self.arg = arg # Declare a function with a parameter x. def display(self, x): print("Python", self.arg, x) # Create an instance of class by passing an argument value to its __init__() method. t = Test("Programming") # Calling the function by passing an argument value. t.display("Book")
Output: Parameterized constructor Python Programming Book
# Python program based on the parameterized constructor. class Employee: def __init__(self, name, email, department, age, salary): self.name = name self.email = email self.department = department self.age = age self.salary = salary def display_emp(self): print("Name: ", self.name) print("Email: ", self.email) print("Department: ", self.department) print("Age: ", self.age) print("Salary: ", self.salary) # Outside the class definition. # Creating an instance of the class by passing argument values. emp1 = Employee("Mahika", "mahika@company_name.com", "Finance", 21, 50000) # Calling the function. emp1.display_emp() print() # Creating another instance of the class by passing different argument values. emp2 = Employee("Alex", "alex@company_name.com", "HR", 30, 70000) # Calling the function. emp2.display_emp()
Output: Name: Mahika Email: mahika@company_name.com Department: Finance Age: 21 Salary: 50000 Name: Alex Email: alex@company_name.com Department: HR Age: 30 Salary: 70000
Some More Example Programs
Let us take some more advanced example program based on the parameterized constructor.
class Student: science = 0 maths = 0 english = 0 computer = 0 hindi = 0 totalMarks = 0 def __init__(self, s, m, e, c, h): self.science = s self.maths = m self.english = e self.computer = c self.hindi = h def totalMarks(self): self.totalMarks = self.science + self.maths + self.english + self.computer + self.hindi print("Total marks obtained = ", self.totalMarks) per = self.totalMarks / 5 print("Percentage = ", per) # Outside the class definition. # Creating an object of class Student. st = Student(89, 90, 97, 79, 99) # Calling the function. st.totalMarks()
Output: Total marks obtained = 454 Percentage = 90.8
# Python program to count how many objects are created. class Count: num = 0 def __init__(self, var): Count.num += 1 self.var = var print("Object value = ", self.var) print("Count of object created = ", Count.num) # Creating multiple objects of the class by passing different values to its __init__() function. c1 = Count(10) c2 = Count(20) c3 = Count(30)
Output: Object value = 10 Count of object created = 1 Object value = 20 Count of object created = 2 Object value = 30 Count of object created = 3
In this example, class variable num is shared by all three objects of the class Count. Initially, it is initialized with zero. Each time object is created, the num is incremented by 1. As the class variable is shared by all objects, therefore, change maded to num by one object is appeared in other objects as well.
How Constructor Works in Python?
Let’s take an example code to understand the working of constructor and the role of self parameter. Please pay close attention, else, you will not understand it. Look at the below code.
class Employee: def __init__(self, name, age, salary): self.name = name self.age = age self.salary = salary def display(self): print("Name: ", self.name) print("Age: ", self.age) print("Salary: ", self.salary) # Creating an object of class Employee with passing arguments to its constructor. emp = Employee("John", 25, 50000) # Calling function. emp.display()
Output: Name: John Age: 25 Salary: 50000
Let’s understand how the constructor works in Python.
(1) When we use the class name along with parentheses and some argument values, the constructor gets called. Python creates a new, empty Employee object in the stack memory. It does not have any data attributes right now.
(2) Next, arguments are passed to the __init__() function. Then, Python takes the newly created object and passes it as the first argument, which we named self. In other word, Python assigns the newly created object to the parameter self, as shown in the figure.
(3) Now, the body of the constructor is executed. We assign each parameter (name, age, and salary) to an attribute of the same name in the instance of Employee object using dot notation.
Since the self is referring to the new Employee object, therefore, we use self to assign each parameter name, age, and salary to attributes of the same name in the Employee object.
After it, all the arguments we passed to the constructor will be assigned to attributes (i.e. variables) in the Employee object. They will be like this:
self.name = 'John' self.age = 25 self.salary = 50000
Look at the memory in the figure.
(4) When the execution of constructor completes, Python takes the Employee object and returns it as a result of calling constructor. In this case, when Employee object is returned, it is assigned to the reference variable emp, Look at the above figure to understand better.
Multiple Constructors in a Class
Python allows us to define two or more similar constructors in a class. If we define many similar constructors in the class, the instance of the class will always call the last constructor. Let’s take a very simple example based on it.
# Python program based on multiple constructors. class Demo: # Define the first constructor. def __init__(self): print("First constructor") # Define the second constructor. def __int__(self): print("Second constructor") # Define third constructor. def __init__(self): print("Third constructor") # Outside the class definition. # Creating an instance of class Demo. d = Demo()
Output: Third constructor
In this example, we have defined three constructors of the same type. The object d is called the last constructor in the following code, even though all constructors have the same configuration. The object d has not have the access to the first and second constructor. Internally, the object of the class will always call the last constructor if the class has several similar type constructors.
Note: Python does not support constructor overloading mechanism as in Java does.
In this tutorial, we have explained constructor in Python and its types with the help of example programs. Hope that you will have understood the basic points of constructor and practiced all programs.
Thanks for reading!!!