Explaining Constructor in Python With an Example
Classes and Objects are the things that define Object-Oriented Programming Languages, and Constructor and Destructors are the ones that define Classes and Objects.
In this article, we will briefly discuss what Constructor are, How to invoke them, their types, and How to Create them with real-time code examples.
What are Constructor in Python?
Constructors are Basic Building Blocks of Python, Precisely A class. Constructors are used to initialize variables of a class so that the class variables do not point to a rubbish value before assigning values to it. By doing this, Some are initialized to zero and other to the specific values given by the user. In Python, the “__init__” method is used to define a constructor. We do not need a separate calling statement to call a constructor, It is called whenever we create an object to the class.
Syntax of constructor declaration :
The “__init__” method is used to declare a constructor in python. It can be used simply using the “def” keyword in the code, just like a function.
Syntax
class virat:
def __init__():
score = 0
Code language: Python (python)
Function Of Constructor
The function of a constructor is to assign the default values to a constructor so that whenever the object is created, a constructor is invoked automatically and default values will be assigned to it.
Types Of Constructor in Python
There are two types of constructors in python, namely,
- Default Constructor
- Non-Default Constructor
Default Constructor
A default constructor is a constructor which takes no argument while defining the function. An example can be seen below.
Example
class virat:
def __init__(self):
#Default Constructor
self.score = 0
def get_score(self):
return self.score
king = virat()
print(king.get_score())
Code language: Python (python)
Click Here to run the code!
OUTPUT
0
Code language: Python (python)
Non-Default Constructor
Non-Default Constructors can also be called as Parameterized Constructors, meaning we can send values to the constructors while creating an object.
Example
class virat:
def __init__(self, score):
# Parameterized Constructor
self.score = score
def get_score(self):
return self.score
king = virat(100)
print(king.get_score())
Code language: Python (python)
Click Here to run the code!
OUTPUT
100
Code language: Python (python)
Parameterized Constructor
A parameterized Constructor is a non-default constructor. It takes arguments while creating the object. The Syntax can be seen below.
Syntax
def __init__(self, Parameters 1 , parameter 2):
#statements
Code language: Python (python)
An example of the parameterized constructor is discussed in the above section.
Non-Parameterized Constructor
A Non-Parameterized constructor is a simple default constructor. It takes no arguments. The syntax is almost the same as parameterized constructor except for the parameters part.
Syntax
def __init__(self):
#statements
Code language: PHP (php)
Creating a Constructor in Python
We can create a constructor by using the def keyword, which is often used for defining a function in python. As a Constructor is also a special method, we can create the same. The difference comes here, the function name of a constructor is always “__init__”.
Example Code
class virat:
def __init__(self):
#Constructor
self.score = 0
def get_score(self):
return self.score
king = virat()
print(king.get_score())
Code language: Python (python)
Click Here to run the code!
OUTPUT
0
Code language: Python (python)
Constructors can have how many parameters?
A Constructor can have any number of parameters, starting from zero to any number until the memory is full, or the requirement is met.
Difference between parameterized and non-parameterized constructors
Parameterized Constructor | Non-Parameterized Constructor |
---|---|
It is a type of Non-Default Constructor. | It is a type of Default Constructor. |
It can take any number of arguments. | It does not take any parameters. |
Parameterized Constructors can be divided into types they are namely, Positional and Keyword Constructors. | Non-Parameterized constructors are not divided further. |
Counting the number of Objects in a class
This can be called a classical problem of constructors. We can solve this by simply learning the concept of Constructors. As we have discussed a constructor is invoked whenever an object is created, Hence, we initialize a variable count to count how many times an object is invoked which is, in turn, the number of objects created.
Code
class Point:
count = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
Point.count += 1
point1 = Point(103, 202)
point2 = Point(3320, 420)
point3 = Point(5230, 60)
print(Point.count)
Code language: Python (python)
Click Here to run the code!
OUTPUT
3
Code language: Python (python)
Several constructors in a single class Using Python’s Built-in class functions
In Python, it is possible to define multiple constructors in a single class using the @classmethod
decorator. A class method is a method bound to the class and not the instance of the class.
Here is an example of how you can define multiple constructors in a single class using class methods in Python:
Example Code
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
@classmethod
def from_tuple(cls, coords):
return cls(coords[0], coords[1])
@classmethod
def from_dict(cls, coords):
return cls(coords['x'], coords['y'])
point1 = Point(10, 20)
point2 = Point.from_tuple((30, 40))
point3 = Point.from_dict({'x': 50, 'y': 60})
print(point1.x, point1.y)
print(point2.x, point2.y)
print(point3.x, point3.y)
Code language: Python (python)
Click Here to run the code!
OUTPUT
10 20
30 40
50 60
Code language: Python (python)
Built-in class attributes
In Python, every class has a number of built-in attributes that can be accessed using the dot notation. Some of the most commonly used built-in class attributes are:
__doc__
: This attribute holds the documentation string of the class if one is provided.__name__
: This attribute holds the name of the class as a string.__module__
: This attribute holds the name of the module in which the class is defined as a string.__dict__
: This attribute is a dictionary that holds the namespace of the class. It contains the names and values of the class’s attributes and methods.__bases__
: This attribute is a tuple that holds the base classes of the class.
Here is an example of how you can access these attributes in Python:
Code
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
print(Point.__doc__)
print(Point.__name__)
print(Point.__module__)
print(Point.__dict__)
print(Point.__bases__)
Click Here to run the code!
OUTPUT
Point
__main__
{'__module__': '__main__', '__doc__': 'A simple class for representing a point in 2D space', '__init__': <function Point.__init__ at 0x7f57f3556f80>, '__dict__': <attribute '__dict__' of 'Point' objects>, '__weakref__': <attribute '__weakref__' of 'Point' objects>}
()
Code language: Python (python)
Conclusion
In this article, we have discussed constructors and their types and differences among them. Later, we discussed about Creating several constructors using inbuilt methods and Class Attributes.
Frequently Asked Questions to Resolve (FAQs)
What are constructors in Python?
In Python, a constructor is a special method that is automatically called when an object of a class is created. It is used to initialize the attributes of the object. The constructor method is named init and it is defined within the class definition.
How do Python constructors work?
Constructors are involved whenever an object is created. When a new object is created using the class, the init method is automatically called with the newly created object as the first argument and any additional arguments are passed to the class constructor. The init method can then use the self keyword to initialize the attributes of the object.
What is the purpose of Python constructors?
The main purpose of constructors in Python is to initialize the attributes of an object when it is created. The constructor method init is called automatically when a new object is created using a class and it allows you to set the initial state of the object by defining the values of its attributes. This is particularly useful when you want to ensure that every object of a class has certain attributes set to specific values when it is created.
How are Python constructors used?
In python, Constructors can be used to initialize attributes of a particular class and also to allocate memory to an object using the init method.
What are the applications of Python constructors?
In Python, constructors are used in initializing an object’s state when it is first created. The constructor method is called automatically when an object of the class is created. The constructor method is defined using the init() method, and it takes self as the first parameter.
Sharing is caring
Did you like what Krishna Bethina wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses:
303 students learning
Haris
Python Crash Course for Beginners
Surendra varma Pericherla
Learn Data Structures Using Python