- Python Constructor Tutorial [Easy Examples]
- Getting started with Python constructor
- Creating a constructor in Python
- Python default constructor
- Python non-parameterized constructor
- Example of Python non-parameterized constructor
- Python parameterized constructor
- Example of Python parameterized constructor
- Counting the number of objects of class using Python constructor
- Multiple Python constructors in a single class
- Summary
- Further Reading
- Leave a Comment Cancel reply
- Python Tutorial
Python Constructor Tutorial [Easy Examples]
A Python constructor is a special kind of method that calls when it instantiates an object using the definitions found in the class. Python relies on the constructor to perform tasks such as initializing (assigning values to) any instance variables that the object will need when it starts. In this tutorial, we will learn about the Python constructor along with different scenarios. We will discuss different types of Python constructors including default one, parameterized, and non-parameterized constructor.
We will also cover how we can count the number of objects using the constructor. Moreover, we will also discuss multiple class constructors and different built-in attributes. In a nutshell, this tutorial will contain all the necessary details and examples that you need to know in order to start working with a Python constructor.
Getting started with Python constructor
As we already discussed that the Python constructor is a method that is called when an object is created. This method is defined in the class and can be used to initialize basic variables. This class is called each time we create a new object. For example, if we create four objects, the class constructor will be called four times. Every class has a constructor, but it is not required to explicitly define it. The simple syntax of the Python constructor looks like this:
def init(self): # method statements
The Python constructor always has a name init and the name init is prefixed and suffixed with a double underscore( __ ). We declare a constructor using def keyword, just like methods.
Creating a constructor in Python
As we discussed, in Python, the method __init__() simulates the constructor of the class. This method is called when the class is instantiated. It accepts the self-keyword as a first argument which allows accessing the attributes or method of the class. Now let us take an example and see how we can use a Python constructor. See the example below:
# python class class Student: # creating Python constructor def __init__(self, name, age): # variables self.name = name; self.age = age; # Python class method def Print(self): # printing the name and age print("Student name is :", self.name) print("Student age is : ", self.age) # creating object of type Student student = Student('XYZ', 22) # calling the Print method student.Print()
Student name is : XYZ Student age is : 22
In the above example, first, we created a python class and then defined a constructor which takes 2 arguments. Then we defined a class method that just prints the name and age, that we have passed to the constructor. Then, in the end, we created a new object of type Student and class its Print method to print the name and age.
Python default constructor
When we do not include the constructor in the class or forget to declare it, then that becomes the default constructor( no constructor at all). It does not perform any task but initializes the objects. See the example below which does not have any explicit constructor.
# python class class Student: # python class method def Print(self, name, age): # printing print("The name of student is:", name) print("The age of student is : ", age) # creating object of type Student student = Student() student.Print("XYZ", 22)
The name of student is: XYZ The age of student is : 22
Notice that in the above program, there is no any explicitly mentioned constructor but there is a default constructor which function is to initialize the object.
Python non-parameterized constructor
The constructors that have an empty parameter are known as non-parameterized constructors. They are used to initialize the object with default values or certain specific constants depending upon the user. The non-parameterized constructor uses when we do not want to manipulate the value or the constructor that has only self as an argument. The simple syntax of the python non-parameterized constructor is as follows:
The non-parameterized constructor does not take any arguments.
Example of Python non-parameterized constructor
Now let us take an example of a Python constructor without any arguments. See the example below:
# python class class Student: # creating Python constructor def_init_(self): print("This is python constructor without arguments!!") # creating object of type Student student = Student()
This is python constructor without arguments!!
Notice that we did not call the __init__() method but still it was executed because the constructor executes each time an object is created.
Python parameterized constructor
The constructor with parameters is known as parameterized constructor. The parameterized constructor takes its first argument as a reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer. The simple syntax of the Python parameterized constructor is as follows:
def_init (self, arg1, arg2, . argn): # statements
Notice we can define as many parameters as we want in our Python constructor.
Example of Python parameterized constructor
Let us now take an example of a Python constructor with arguments. See the Python program below which takes has a constructor that takes multiple arguments.
# python class class Student: # creating Python constructor def __init__(self, total_marks, obtain_marks): self.total_marks = total_marks self.obtain_marks = obtain_marks # Python class method def marks(self): # printing print("Total marks are : ",self.total_marks) print("Obtain marks are :", self.obtain_marks) # creating object of type Student student = Student(100, 84) # calling marks method student.marks()
Total marks are : 100 Obtain marks are : 84
In the example above, you can see that our constructor takes two arguments apart from the self keyword.
Counting the number of objects of class using Python constructor
We already discussed that the constructor is called automatically when we create the object of the class. That means each time, we create an object, the constructor will be called. We can use a python constructor to count the number of objects of a class because it will be called each time. See the Python program below, which counts the number of Objects.
# python class class Student: counts = 0 # creating Python constructor def __init__(self, total_marks, obtain_marks): self.total_marks = total_marks self.obtain_marks = obtain_marks # Incrementing the counts each time this constructor is called Student.counts +=1 # creating object of type Student student1 = Student(100, 84) student1 = Student(100, 83) student1 = Student(100, 84) student1 = Student(100, 86) student1 = Student(100, 46) student1 = Student(100, 45) # printing the total object counts print("the total number of objects are : ", Student.counts)
the total number of objects are : 6
So, each time the new object is created, the constructor is automatically called so we increment the count value each time, the constructor is called.
Multiple Python constructors in a single class
We have already learned a lot about the Python constructor and understood it through various examples. But what if we try declaring more than one similar constructor in the Class. See the example below, where we had declared two constructors in a single Python class.
# python class class Student: # creating Python constructor 1 def __init__(self): # printing print("this is the first constructor!") # python constructor 2 def __init__(self): # printing print("this is the second constructor!") # creating object of type Student student1 = Student()
this is the second constructor!
In the above Python program, we have defined a class and declared two constructors with the same configuration. We have then created the object called student, but it cannot access the first method. Internally, the class object will always call the last constructor if the class has more than one constructor. If we will create multiple constructors with a different number of arguments and will try to create an object, it will return an error. See the example below:
# python class class Student: # creating Python constructor 1 def __init__(self): # printing print("this is the first constructor!") # python constructor 2 def __init__(self, two): # printing print("this is the second constructor!") # python constructor 3 def __init__(self, two, three): # printing print("this is the third constructor!") # creating object of type Student student1 = Student()
It gives an error because we did not provide two arguments to the object while our last constructor need two arguments. If we will provide the two arguments, it will not return any error. See the example below:
# python class class Student: # creating Python constructor 1 def_init_(self): # printing print("this is the first constructor!") # python constructor 2 def_init_(self, two): # printing print("this is the second constructor!") # python constructor 3 def_init_(self, two, three): # printing print("this is the third constructor!") # creating object of type Student student1 = Student(1, 3)
this is the third constructor!
As we already discussed that if we will create multiple constructors then the very last constructor will be executed, and in the above example the last constructor takes two arguments.
Summary
A constructor is a special kind of method which is used for initializing the instance variables during object creation. It will be executed each time a new object is created. In this tutorial, we learned about Python constructor and we covered various examples with different scenarios. We discussed how we can create a constructor with and without multiple arguments which are also called parameterized and non-parameterized constructors. At the same time, we also discussed how we can use the constructor to count the number of objects of a class. Moreover, we learned what will be the effect of multiple constructors.
To summarize, this tutorial contains all the necessary details and sub-topics that are important to start working with Python object-oriented programming.
Further Reading
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Leave a Comment Cancel reply
Python Tutorial
- Python Multiline Comments
- Python Line Continuation
- Python Data Types
- Python Numbers
- Python List
- Python Tuple
- Python Set
- Python Dictionary
- Python Nested Dictionary
- Python List Comprehension
- Python List vs Set vs Tuple vs Dictionary
- Python if else
- Python for loop
- Python while loop
- Python try except
- Python try catch
- Python switch case
- Python Ternary Operator
- Python pass statement
- Python break statement
- Python continue statement
- Python pass Vs break Vs continue statement
- Python function
- Python call function
- Python argparse
- Python *args and **kwargs
- Python lambda function
- Python Anonymous Function
- Python optional arguments
- Python return multiple values
- Python print variable
- Python global variable
- Python copy
- Python counter
- Python datetime
- Python logging
- Python requests
- Python struct
- Python subprocess
- Python pwd
- Python UUID
- Python read CSV
- Python write to file
- Python delete file
- Python any() function
- Python casefold() function
- Python ceil() function
- Python enumerate() function
- Python filter() function
- Python floor() function
- Python len() function
- Python input() function
- Python map() function
- Python pop() function
- Python pow() function
- Python range() function
- Python reversed() function
- Python round() function
- Python sort() function
- Python strip() function
- Python super() function
- Python zip function
- Python class method
- Python os.path.join() method
- Python set.add() method
- Python set.intersection() method
- Python set.difference() method
- Python string.startswith() method
- Python static method
- Python writelines() method
- Python exit() method
- Python list.extend() method
- Python append() vs extend() in list
- Create your first Python Web App
- Flask Templates with Jinja2
- Flask with Gunicorn and Nginx
- Flask SQLAlchemy