Constructor in Python with Examples
FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!
In Object-Oriented Programming, a constructor is a special kind of method used to instantiate an object. The primary objective of Constructors is to assign values to the instance attributes of the class.
Constructors provide state and uniqueness to the objects. Without constructors, all objects will have the same values and no object will be unique.
In languages such as Java and C++, constructors are created by defining a method with the same name as the Class. In Python, constructors do not depend on the name of the class because they have their own name init and we can create a constructor by defining the __init__() method.
Python automatically invokes the constructor whenever we create an object. Python calls the __new__() method followed by the __init__() method as soon as we create an object. __new__() creates the object while __init__() instantiates the created object.
Creating a Constructor in Python
To create a constructor in Python, we need to define a special kind of magic method called __init__() inside our class.
By default, this method takes one argument known as self. Self takes the address of the object as its argument and it is automatically provided by Python. We can define as many parameters as we need.
Syntax for creating constructor in Python
class ClassName: def __init__(self): # Method body
Example of Python Constructor
class PythonGeeks: def __init__(self): print("Object Created for the Class PythonGeeks") obj1 = PythonGeeks()
Output
In the above code example, we created a constructor by defining the __init__() method. By looking at the output, we can tell that the constructor is called as soon as we created the object.
Types of Constructor in Python
We have three types of constructors in Python: Non-Parameterized, Parameterized, and Default Constructors.
1. Non-Parameterized Constructor in python
Constructors with no parameters other than self are called Non-Parameterized Constructors. The values of attributes inside the non-parameterized constructors are defined when creating the class and can not be modified while instantiating.
Example of Non-Parameterized Constructor in Python
class Dress: def __init__(self): self.cloth = "Cotton" self.type = "T-Shirt" def get_details(self): return f"Cloth = {self.cloth}\nType = {self.type}" t_shirt = Dress() print(t_shirt.get_details())
Output
Cloth = Cotton
Type = T-Shirt
In the above code example, __init__() method doesn’t take any other arguments except self.
2. Parameterized Constructor in Python
Constructors with at least two parameters including self are called Parameterized Constructors. The arguments for the parameters should be passed while creating the object. The values of attributes inside these constructors can be modified while instantiating with the help of parameters. Since the attributes can be modified, each object can have different values and be unique.
Example of Python Parameterized Constructor
class Dress: def __init__(self, cloth, type, quantity=5): self.cloth = cloth self.type = type self.quantity = quantity def get_details(self): return f"{self.quantity} {self.cloth} {self.type}(s)" shirt = Dress("silk", "shirt", 20) t_shirt = Dress("cotton", "t-shirt") print(shirt.get_details()) print(t_shirt.get_details())
Output
5 cotton t-shirt(s)
In the above code example, __init__() method takes multiple parameters and because of this, the objects shirt and t_shirt both have different values.
Non-Parameterized vs Parameterized Constructor in Python
Non-Parameterized Constructor | Parameterized Constructor |
Has only one parameter self | Has minimum two parameters including self |
Attributes can’t be modified while instantiating | Attributes can be modified while instantiating |
Same values for all objects | Different values for different objects |
Mostly used to set default values to attributes | Can be used to dynamically assign different values to attributes |
Can not provide state/uniqueness to objects | It can provide state/uniqueness to objects |
3. Default Constructor in Python
A constructor is a necessary tool for object creation. If we don’t define a constructor, then Python creates a non-parameterized constructor with an empty body. This constructor is called Default Constructor.
Example of Python Default Constructor
class Dress: cloth = "silk" type = "shirt" def details(self): return f"A {self.cloth} {self.type}" shirt = Dress() print(shirt.details())
Output
Although we haven’t created a constructor in the above code example, Python still initialized the object shirt by creating an empty constructor.
Arguments in Python
The __init__() method supports all kinds of arguments in Python.
1. Positional Arguments in Python
Positional arguments pass values to parameters depending on their position. They are simpler and easier to use than other types of arguments.
Example of Python Positional Arguments
class Dress: def __init__(self, type, price): self.type = type self.price = price def details(self): return f"A {self.type} costs Rs.{self.price}" shirt = Dress("shirt", 50) print(shirt.details())
Output
In the above code example, we used positional arguments to instantiate the object.
2. Keyword Arguments in Python
Arguments which should be passed by using a parameter name and an equal to sign are called keyword arguments. They are independent of position and dependent on the name of the parameter. These arguments are easier to read and provide better readability.
Example of Python Keyword Argument
class Dress: def __init__(self, type, price): self.type = type self.price = price def details(self): return f"A {self.type} costs Rs.{self.price}" t_shirt = Dress(price=150, type="t-shirt") print(t_shirt.details())
Output
In the above code example, we used keyword arguments to instantiate the object.
3. Arbitrary Argument in Python
Multiple arguments which are passed into a single indefinite length tuple are called arbitrary arguments. We use arbitrary arguments when we don’t know the number of arguments that will be passed to the function.
Example of Python Arbitrary Argument
class Dress: def __init__(self, *types): self.types = types def details(self): return self.types t_shirt = Dress("shirt", "t-shirt") print(t_shirt.details())
Output
In the above code example, we used arbitrary arguments to instantiate the object.
Adding Attributes in Python
We can add new attributes to the constructor even after we instantiated the object.
Example of Adding Attributes in Python
class Dress: def __init__(self): pass shirt = Dress() shirt.size = 10 print(shirt.size)
Output
In the above code example, we created an empty constructor and created an object shirt. After creating the object, we added a new attribute size to the constructor.
Count Objects Using Constructor in Python
Constructors are called everytime we create an object, so we can use them to count the number of objects we created.
We do this by declaring a class attribute to keep count and every time a constructor is called, it increments the class attribute.
Example Counting Objects using Constructor in python
class Dress: def __init__(self): Dress.no_of_dresses += 1 no_of_dresses = 0 print("Before Creating objects") print(f"No of objects = {Dress.no_of_dresses}") for _ in range(10): # To create 10 objects Dress() print("After Creating objects") print(f"No of objects = {Dress.no_of_dresses}")
Output
No of objects = 0
After Creating objects
No of objects = 10
In the above code example, we created 10 objects of the class Dress and using the attribute no_of_dresses and constructor __init__(), we counted the 10 objects.
Overloading in Python
Python doesn’t support Method Overloading. Whenever we define a second constructor, it overrides the first constructor.
Example of Python Overloading
class PythonGeeks: def __init__(self): print("Python") def __init__(self): print("Geeks") geek = PythonGeeks()
Output
In the above code example, the second __init__() method has overridden the first __init__() method and the first __init__() method no longer exists to call.
It doesn’t work even if we use different kinds of constructors by changing the number of parameters.
For Example:
class PythonGeeks: def __init__(self): print("Python") def __init__(self, num): self.num = num print("Geeks") geek = PythonGeeks()
Output
In the above code example, instead of calling the first constructor, Python called the second constructor.
One workaround to achieve overloading-like behavior is to use default arguments.
For Example
class PythonGeeks: def __init__(self, num1, num2=None): self.num1 = num1 self.num2 = num2 if self.num2 is None: print(self.num1) else: print(self.num1 + self.num2) geek = PythonGeeks(6) obj = PythonGeeks(5, 4)
Output
9
In the above code example, __init__() method prints the sum of two arguments if two arguments are passed, otherwise, it just prints the first argument.
Return Statement in Python
Like all other methods, __init__() method also has a return statement but unlike other methods, it can only return None. Trying to return anything other than None raises TypeError. Since returning only None is useless, we never use a return statement in the constructor in Python.
Example of Python Return Statement
class PythonGeeks: def __init__(self): return "PythonGeeks" geek = PythonGeeks()
Output
In the above code example, we tried to return a string rather than None and raised a TypeError.
Importance of Constructor in Python
The use of Constructor in Python is to instantiate the objects. Without constructors, we cannot define new values to new objects. All objects will have the same values and will no longer be unique. Objects will be nothing more than duplicates. To provide uniqueness to the objects, we need constructors.
Constructors are also useful to call any methods while creating the object. This ability can help us in creating more dynamic and complex objects.
For Example
class Square: def __init__(self, length): self.length = length self.area = self.find_area() def find_area(self): return self.length * self.length obj = Square(5) print(obj.area)
Output
In the above code example, instead of calling the function everytime we need to get an area, we use a constructor to automatically call the find_area() function and save the area value as soon as we create an object.
If we need to use the area multiple times, we can simply access the saved value rather than invoking the function multiple times. This helps to prevent invoking the method multiple times.
Method __new__() in Python
People often assume that __init__() is the first method Python calls while creating an object but it is false. To create an object, Python first calls __new__() method to create the object and then calls __init__() method to instantiate the created object.
Example of Python Method__new__()
class Dress: def __new__(cls, *args, **kwargs): print("Object Created") shirt = Dress()
Output
By looking at the above code example, we can clearly understand that __new__() is called as soon as we define an object.
Python Interview Questions on Constructor in Python
Q1. Create a class and make the class print a string “Object Created” whenever we instantiate an object.
Ans 1. Below is the complete code:
class CreateObjects: def __init__(self): print("Object Created") obj1 = CreateObjects()
Output
The above code prints a string whenever we instantiate an object.
Q2. Create a non-parameterized constructor and set the default values for the following attributes:
make = “Aud”
model = “SQ”
doors = 4
wheels = 4
Ans 2. Code is as follows:
class Car: def __init__(self): self.make = "Aud" self.model = "SQ" self.doors = 4 self.wheels = 4 def all_values(self): return f"{self.make}, {self.model}, " \ f"{self.doors}, {self.wheels}" car1 = Car() print(car1.all_values())
Output
Q3. Create a class Triangle and initialize it with height and base and create a method area to return the area of the triangle.
Ans 3. Code is as follows:
class Triangle: def __init__(self, height, base): self.height = height self.base = base def area(self): ans = (self.height * self.base) / 2 return ans triangle1 = Triangle(4, 3) print(triangle1.area())
Output
Q4. Use a return statement in the constructor without raising an error.
Ans 4. Code is as follows:
class ReturnNone: def __init__(self): return None re = ReturnNone() print(re.__init__())
Output
Q5. Change the output of the given code without editing it, add new code to the given code that only prints “New Object Created” when an object is instantiated.
class Blueprint: def __init__(self): print("Object Created with constructor 1") # Write Your Code Here... obj1 = Blueprint()
Output
Ans 5. Code and Output are as follows:
class Blueprint: def __init__(self): print("Object Created with constructor 1") # Write Your Code Here... def __int__(self): print("New Object Created") obj1 = Blueprint()
Output
Quiz on Constructor in Python
Conclusion
In this article, we discussed the constructors in Python. We discussed the types and how to create those different types of constructors. We also learned about the different types of parameters we can use and how overloading works in Python.
Furthermore, if you have any queries or thoughts, please feel free to share them with us in the comment section.
what is that f in return statement ?
hy, i am beginner and try to learn python, i learn a lot of things , which stuck in my mind for many days,
i really feel happy and get inspire