Python class constructor and objects which are the building blocks of this language. We are aware of the fact that python is an object-oriented language. Python has classes which can only one type of data type at a single time. The user can declare a class in Python as:
Python class constructor is that part of the code which comes into play when the user creates a new object of the class. A constructor can be called in two ways. Either it can be done by calling each variable directly from the object. We use dot (.) symbol for this. Another way is by using the self keyword in python.
The constructor can have different values in the member variables. For example name of the class ‘person’, age of the class ‘person’ etc. The constructor in python helps in initialization of the object when we want to start it. Objects can start up any task in the python program assigned to them as a constructor has enough resources. The method used to call constructor is __init__().
Types of constructor in python:
- Default constructors: This constructor in python does not accept any type of arguments. It will contain only one argument in reference to the constructor which is build in the program.
- Parameterized constructors: The constructor which has parameters is known as parameterized constructors. This will only take the first argument as the reference whereas all the other arguments are provided by the user.
Python program to illustrate the use of class constructor
class Addition: a = 0 b = 0 answer = 0 def __init__(self, f, s): self.a = f self.b = s def display(self): print("First number = " + str(self.a)) print("Second number = " + str(self.b)) print("Addition of two numbers = " + str(self.answer)) def calculate(self): self.answer = self.a + self.b obj = Addition(100, 200) obj.calculate() obj.display()
The output of this python program will be:
The first number is = 100 The second number is = 200 Addition operation of two numbers = 300
A constructor will accept the self keyword always as the initial argument and later helps in accessing the methods and attributes of the class. As __init__() method defines, the user can pass as many arguments as we want. There are some inbuilt class functions in python as well. Let us discuss about them.
Python Inbuilt functions
- getattr(obj,name,default): This method will help in gaining access to the attributes of the class.
- delattr(obj, name): In case the user wants to delete an attribute of a class, this method will come into play.
- setattr(obj, name,value): In case the user wants to set a particular value with a specific attribute, he can use setarrr() method. This is hence a built-in function in python.
- hasattr(obj, name): When an object contains an attribute, the user can use this method. The function returns true if an attribute is present in the method.