This article will introduce you to an interesting topic that is simple yet core for programming, I am referring to Python constructors. Following pointers will be covered in this article,
Python Constructors
If you have been programming for sometime now, you have probably come across the name Python one too many times. Python as a programming language follows object orientation, meaning which every instance that is created on the platform is defined as an object. Although most of the components in Python have a ton of information online, one topic that keep getting researched over and over again is that of a constructor in Python. Therefore in this article we will discuss all about constructors in Python, how you can make use of them and the benefits they bring to the table. Let’s begin!
Moving on with this article on Python Constructors,
What is a Constructor in Python?
A constructor can simply be defined as a special type of method or function which can be used to initialize instances of various members in a class.
In Python, there are two different types of constructors.
- Non-parameterized Constructor: The constructors in Python which have no parametres present is known as a non parameterized constructor.
- Parameterized Constructor: A constructor that has a parametre pre defined is known as a parameterized constructor.
A constructor is defined the moment we create an object inside a class. The presence of a constructor also verifies that enough resources are present, so that a start up task can easily be executed via an object of a class.
Moving on with this article on Python Constructors,
Creating a Constructor in Python
Now that you have acquainted yourself with the definition and types of constructors in Python, let us explore how we can create a constructor in Python.
In Python, if you need to create a construct you need to make use of the __init__ function and or method. You need to call upon this method, the moment a class is instantiated. Once the __init__ function has been defined and called upon, we can pass any number of arguments at the time of creating the class objects depending upon your needs. The most common use of a constructor in Python is to initialize the attributes of a class.
Note:
Every class you create in Python needs to have a constructor present in order for it to function, even if it is the default constructor.
To understand this concept better, take a look at the example below.
class Employee: def __init__(self,name,id): self.id = id; self.name = name; def display (self): print("ID: %d nName: %s"%(self.id,self.name)) emp1 = Employee("John",101) emp2 = Employee("David",102) #accessing display() method to print employee 1 information emp1.display(); #accessing display() method to print employee 2 information emp2.display();
When you run the above program, the output will look something like this.
ID: 101
Name: John
ID: 102
Name: David
Moving on with this article on Python Constructors,
Difference between Parameterized and Non Parameterized Constructor
As mentioned in the definitions above, a parameterized constructor is one which has a predefined value and a non parameterized constructor is one which has no value assigned to it. While programming the use cases vary depending upon the context, and to understand this better, take a look at the examples below.
class Student: #Constructor - non parameterized def __init__(self): print("This is non parametrized constructor") def show(self,name): print("Hello",name) student = Student() student.show("John")
The above is an example of a Non-Parameterized Constructor and its output will be the following.
This is non parametrized constructor
Hello John
class Student: #Constructor - parameterized def __init__(self, name): print("This is parametrized constructor") self.name = name def show(self): print("Hello",self.name) student = Student("John") student.show()
The above is an example of a Parameterized Constructor and its output will be the following.
This is parametrized constructor
Hello John
Moving on with this article on Python Constructors,
In Built Class Functions in Python
Now that the basics of a constructor in Python is clear, let us explore the various inbuilt classes that are present in Python.
- getattr(obj,name,default): This in built function in Python is used to gain access to the attributes of a class.
- delattr(obj, name): If you need to delete a specific attribute in a class, then make use of this inbuilt function.
- setattr(obj, name,value): In a certain situation, if you decide to set a particular value to a specific attribute, then make use of this function which comes inbuilt in Python.
- hasattr(obj, name): Last but not least, if you need to see if a particular object contains an attribute, then make use of this function. Upon execution, this will return true if an attribute is present in a function.
To understand the concept of inbuilt class functions in Python, take a look at the code below.
class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age #creates the object of the class Student s = Student("John",101,22) #prints the attribute name of the object s print(getattr(s,'name')) # reset the value of attribute age to 23 setattr(s,"age",23) # prints the modified value of age print(getattr(s,'age')) # prints true if the student contains the attribute with name id print(hasattr(s,'id')) # deletes the attribute age delattr(s,'age') # this will give an error since the attribute age has been deleted print(s.age)
The output for the above will be.
John
23
True
AttributeError: ‘Student’ object has no attribute ‘age’
Moving on with this article on Python Constructors,
Inbuilt Class Attributes
Along with the inbuilt class functions, Python comes with inbuilt class attributes, which come in handy at times. Some of the most significant builtin class attributes are as given below.
- __dict__: By using this you can view the dictionary that contains information regarding the class namespace.
- __name__: Use this attribute, if you need to view the name of the current class.
- __doc__: This attribute contains a string, which has the documentation for the current class.
- __module__: If you need to access the module in which the class is defined make use of this inbuilt attribute.
- __bases__: If you need to view the tuple which includes all the base classes, then use this function.
An example to clarify all the built in class attributes is as given below.
class Student: def __init__(self,name,id,age): self.name = name; self.id = id; self.age = age def display_details(self): print("Name:%s, ID:%d, age:%d"%(self.name,self.id)) s = Student("John",101,22) print(s.__doc__) print(s.__dict__) print(s.__module__)
This brings us to the end of this article on Python Constructors.
To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.
Got a question for us? Mention them in the comments section of “Python Tutorial” and we will get back to you.