Table of Content
- What is a Constructor?
- Characteristics of Using a Constructor in Python OOP
- How to Create a Constructor in Python
- What are the Types of Constructors
- Overloading a Constructor in Python
- Chaining Constructors in Python
- How to Count the Number of Objects of a Class
- What is the Return Value of a Constructor in Python?
- Conclusion and Quick recap
A constructor is a special method used to create and initialize an object of a class.
In this lesson, you will learn how to create a constructor, undertand the different types of constructors, and constructor overloading and chaining.
What is a Constructor?
A constructor is a special method that is used to create and initialize an object of a class.
In object-oriented programming, this method is defined in the class.
The main reason we need a constructor is to declare and initialize instance variables of a class.
The constructor contains a collection of statements that executes at the time of object creation to initialize the attributes of an object.
The instantiation of an object in python is divided into two phases: Object Creation and Object initialization
Internally, the __new__
is the method that creates the object. And, using the __init__()
method we can implement a constructor to initialize the object.
For example:
When we execute tesla = Car()
, Python gets to know that tesla is an object of class Car
and calls the constructor of that class to create an object.
Characteristics of Using a Constructor in Python OOP
- The constructor executes only once for each object during its instantiation. For example, if we create twenty objects, the constructor is called twenty times, once for each object.
- Every class in Python must have a constructor. However, it is not mandatory to explicitly define it when creating a class. Defining the constructors in a class is optional.
- Python implicitly provides a default constructor when a constructor is not defined.
How to Create a Constructor in Python
Syntax of a constructor
def __init__(self):
# body of the constructor
def
: This is the keyword used to define a function.__init__()
Method is a special method for creating a constructor in Python and gets called as soon as an object of a class is instantiated.self
: Theself
parameter refers to the current object. It is always the first parameter in every instance method. It binds the instance to the__init__()
method.
Note: The __init__()
method arguments are optional. We can define a constructor with any number of arguments.
Example of Creating a Constructor in Python
class Car:
# constructor
# initialize instance variable
def __init__(self, model, brand, color):
# instance variables
self.model = model
self.brand = brand
self.color = color
def info(self):
print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
# Instance of tesla accessing instance methods and variable
tesla = Car("Y", "Tesla", "Black")
tesla.info()
# Output
# Model: Y Brand: Tesla Color: Black
When you run the code in the above example, an object tesla
is created using the constructor in the Car class.
The object is created using the __new__()
method.
While creating the tesla
object, three values model
, brand
, and color
are passed as arguments to the __init__()
method.
This is responsible for initializing the tesla
object.
With that, the object is ready to use to access, modify or delete various objects of the Car class.
What are the Types of Constructors
In Python, we have three types of constructors.
1. Default Constructor
This is the default constructor that Python implicitly provides when a class is defined without a constructor.
It is an empty constructor without a body that does not carry out any other task apart from initializing the objects.
The default constructor will not be present in the source py file.
It is inserted into the code when compiled by the Python interpreter.
However, if there is a constructor in the class, the default constructor will not be implicitly added.
Example of a class that uses a default constructor:
class Car:
def info(self):
print('Model:', "Y", 'Brand:', "Tesla", 'Color:', "Black")
# Instance of tesla accessing instance methods and variable
tesla = Car()
tesla.info()
# Output
# Model: Y Brand: Tesla Color: Black
In the above example, we did not define a constructor in the Car
class.
But, we can create an object for the class because a default constructor is implicitly added by Python when the program compiles.
2. Non-Parametrized Constructor
This is a constructor that is defined in a class without parameters. As a result, it doesn't accept any arguments during object creation.
It usually has only the default self
parameter defined and initializes every object with the same set of values.
It is commonly used to initialize each object with default or constant values.
class Car:
def __init__(self):
self.model = "Y"
self.brand = "Tesla"
self.color = "Black"
def info(self):
print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
# Instance of tesla accessing instance methods and variable
tesla = Car()
tesla.info()
# Output
# Model: Y Brand: Tesla Color: Black
In the above example, we defined a constructor in the Car
class with no parameters and explicitly stated the values.
And when we created the object, we did not need to initialize it with custom arguments.
These values can still be accessed, modified, and deleted as we choose.
3. Parameterized Constructor
This is a constructor that is defined in a class with parameters.
Since we can define any number of parameters to the constructor, this constructor is best used when we want to initialize the object with custom values.
The first parameter of a constructor is always self
, and it is a reference to the object being constructed.
For example, consider a company that contains thousands of employees. In this case, while creating each employee object, we need to pass a different name, age, and salary. In such cases, use the parameterized constructor.
class Car:
def __init__(self, model, brand, color):
# instance variables
self.model = model
self.brand = brand
self.color = color
def info(self):
print('Model:', self.model, 'Brand:', self.brand, 'Color:', self.color)
# Instance of tesla accessing instance methods and variable
tesla = Car("Y", "Tesla", "Black")
tesla.info()
# Output
# Model: Y Brand: Tesla Color: Black
In the above example, an object tesla
is created using the constructor in the Car class using three parameters model
, brand
, and color
.
The custom values for these constructors also are passed as arguments.
Overloading a Constructor in Python
Constructor overloading occurs when you define more than one constructor with a different parameters list in such a way that each constructor performs different tasks.
Python does not support constructor overloading.
When multiple constructors are defined in Python, the Python interpreter will only consider the last constructor.
Also, it throws an error when the sequence of the arguments passed to the class during initialization does not match the last constructor.
Example of constructor overloading in Python
class Car:
# constructor with one parameter
def __init__(self, model):
print("One argument constructor")
self.model = model
# constructor with two parameters
def __init__(self, model, brand):
print("constructor with two parameters")
self.model = model
self.brand = brand
# constructor with three parameters
def __init__(self, model, brand, color):
print("constructor with three parameters")
self.model = model
self.brand = brand
self.color = color
# creating the first object
tesla1 = Car("Y", "Tesla", "Black")
# creating the Second object
tesla2 = Car("Y", "Tesla")
Output
In the code sample above, we defined multiple constructors with different arguments.
During object creation, the interpreter executes the last constructor because internally, the object of the class will always call the last constructor, even if the class has multiple constructors.
Next, when we created another object and called a constructor with two arguments, we got a type error.
Chaining Constructors in Python
Constructor chaining is the process of calling one constructor from another constructor.
It is useful when you want to invoke multiple constructors by initializing only one instance.
You will mostly see this in Python OOP inheritance.
When an instance of a child class is initialized, the constructors of all the parent classes are first invoked before the constructor of the child class.
We use the super()
method to invoke the parent class constructor from a child class.
Example of chaining a constructor in python
class Vehicle:
# Constructor of Vehicle
def __init__(self, category):
print('Inside Vehicle Constructor')
self.category = category
class Car(Vehicle):
# Constructor of Car
def __init__(self, category, brand):
super().__init__(category)
print('Inside Car Constructor')
self.brand = brand
class ElectricCar(Car):
# Constructor of Electric Car
def __init__(self, category, model, brand):
super().__init__(category, brand)
print('Inside Electric Car Constructor')
self.model = model
# Object of electric car
tesla = ElectricCar('Electric Car', "Y", "Tesla")
print(f'Category: {tesla.category}, Model: {tesla.model}, Brand={tesla.brand}')
Output:
How to Count the Number of Objects of a Class
To count the number of objects of a class, add a counter in the constructor, which increments by one after each object is created.
Example
class Car:
counter = 0
def __init__(self):
Car.counter = Car.counter + 1
# creating objects
c1 = Car()
c2 = Car()
c2 = Car()
print("The number of Cars:", Car.counter)
Output
The number of cars: 3
What is the Return Value of a Constructor in Python?
In Python, the constructor implicitly returns None
.
Therefore, while declaring a constructor, we do not specify a return type or a return statement.
If we try to return a non-None value from the __init__()
method, it will raise a TypeError.
Example
class ID:
def __init__(self, id):
self.id = id
return True
d = ID(1)
Output
TypeError: init() should return None, not 'bool'
Wrap Off
In this lesson, we learned constructors and used them in object-oriented programming to design classes and create objects.
A constructor is a unique method used to initialize an object of the class. Python will provide a default constructor if no constructor is defined.
Constructor is not a method and doesn't return anything. it returns None.
If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.
Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.