Constructor concepts in python

By

 A Constructor is a special type of method which is used to initialize the object of the class.In c++ and java ,the constructor is the same name as its class.But in python,it is different .Hence we use __init__() as a special method to simulates the constructor of the class.This special method is called when the object of the class is created.

  • The __init__() method accepts the self keyword as a first argument which is used to access the methods or attributes of the class.
  • We can pass the any number of arguments at the time of object creation according to definition of __init__() method.
  • The constructors are mainly used to initialize the class attributes.
  • In python,every class must have a constructor even it may be a default constructor.
Types of the constructor
There are two types of constructor in python.
  1. Parameterized constructor  
  2. Non Parameterized constructor
     1.) Parameterised constructor:-
We can pass multiple parameters in constructor (__init__()) along with self.
e.g.
class student:
    def __init__(self,n,a,s):
        self.name=n
        self.age=a
        self.salary=s
    def show_data(self):
        print(self.name)
        print(self.age)
        print(self.salary)
#Creating the first instance of the class
s1=student("Raj",20,10000)
s1.show_data()
print("")
s1=student("Neha",25,20000)
s1.show_data()
print("")
#Creating the second instance of the class
s2=student("mohan",40,40000)
s2.show_data()
Output:-
Raj
20
10000

Neha
25
20000

mohan
40
40000
>>> 
Description:-
  • Here i have passed 4 parameter along with self in  __init_() constructor.
  • When we create object of the  student class s1 ,s2 with 3 parameter.then this__ init__ () method is called automatically.It is used to initialize the attributes (name,age,salary) of the student class. 
     2.) Non-Parameterised constructor:-
We can use Non-Parameterized constructors according to our requirement.Suppose we do not manipulate/change the value of class then we generally use non parameterized constructors.This constructor pass only self as an argument.
e.g.
class employee:
    def __init__(self):
        print("i am non-parameterized constructor")
        a=5
        b=6
        c=a+b
        print("Result of a and b addition = ",c)
#display() is normal method which takes one argument except self.
    def display(self,name):
        print("Employee name is:",name)
#Creating the object/instance of the class
e1=employee()
e1.display('Ramesh')
Output:-
i am non-parameterized constructor
Result of a and b addition =  11
Employee name is: Ramesh
>>> 
Python default Constructor:-
When we do not declare the constructor (parameterized or non-parameterized) in class then python provides a default constructor or __init__() method.This is known as default constructor in python.This is used to initialize the objects/attributes.
e.g.
class student:
       id=501
       name='Sachin'
       age=20
       def display_data(self):
        print("student id is:",self.id)
        print("student name is:",self.name)
        print("student age is:",self.age)
#Creating the object/instance of the class
s1=student()
s1.display_data()
Output:-
student id is: 501
student name is: Sachin
student age is: 20
>>> 
Description:-
  • Here i have initialize the student class attributes(id,name,age) with the help of default constructor in python.
  • Here i have not used __init__() constructor to initialize the student class attributes.
How to use more than one constructor in a single class:-
We use more than one constructor in a single class but number of argument pass to the __init__() method will be same for all. Mean signature of all constructor (__init__()) will be same.When we create the object of the class,then the last constructor will be call always.
e.g.
class student:
       def __init__(self,n,a):
        self.name=n
        print("student name is:",self.name)
        print("I am first constructor")
       def __init__(self,n,a):
        self.name=n
        self.age=a
        print("I am second constructor")
        print("student name is:",self.name)
        print("student age is:",self.age)      
#Creating the object/instance of the class
s1=student('Ramesh',20) 
print("")
s2=student('Sachin',40)
print("")
s3=student('neha',50)
Output:-
I am second constructor
student name is: Ramesh
student age is: 20

I am second constructor
student name is: Sachin
student age is: 40

I am second constructor
student name is: neha
student age is: 50
>>> 
Note:- The constructor overloading is not possible in python.

Python Built-in class methods:-
There are some builtin method is used in python as given below:-
1.) getattr(obj,name,default):- It is used to access the attributes of the object.
2.) setattr(obj,name,value):- It is used to set a value to the attribute of an object.
3.) hasattr(obj,name):-It return true value if object contains this attribute in the class otherwise return false.
4.) delattr(obj,name):-It is used to delete a specific attribute of the class.
e.gg.
class student:
    def __init__(self,n,age,sal):
        self.name=n
        self.age=age
        self.salary=sal
#creating object of the class
s1=student('Ram',20,3000)
# print the attribute name of the object
print(getattr(s1,'name'))
#Modify the attribute  age to 30
setattr(s1,'age',30)
print(s1.age)
#check whether student contains the attribute value 'sal'
print("Is 'salary' attribute present in student class: ",hasattr(s1,"salary"))
print("Is 'age' attribute present in student class: ",hasattr(s1,"age"))
#delete the attribute 'salary'
delattr(s1,'salary')
print(s1.salary)
Output:-
Ram
30
Is 'salary' attribute present in student class:  True
Is 'age' attribute present in student class:  True
Traceback (most recent call last):
  File "C:/Users/RAMASHANKER VERMA/Desktop/class built methods.py", line 18, in <module>
    print(s1.salary)
AttributeError: 'student' object has no attribute 'salary'
>>> 
Built-in class attributes:-
Python class contains some built-in class attributes which is used to provide the information of the current class.
There are some built-in class attributes as given below:-
1.) __doc__():- It is used to print the doc string of the class.
2.) __class__ :-It is used to access the module name and class name.
3.) __dict__ :- It is used to provide dictionary containing the information of the class.
4.) __module__():- It prints the module name in which this class is defined. 
e.g.
class student:
    "This is MNT LAB Tutorials"
    def set_data(self,id,n,a):
        self.id=id
        self.name=n
        self.age=a
#ceating the object of the class
s1=student()
s1.set_data(102,'Ramesh singh',30)
print(s1.__doc__)
print(s1.__dict__)
print(s1.__module__)
print(s1.__getattribute__)
print(s1.__format__)
print(s1.__class__)
print(s1.__eq__)
Output:-
This is MNT LAB Tutorials
{'id': 102, 'name': 'Ramesh singh', 'age': 30}
__main__
<method-wrapper '__getattribute__' of student object at 0x0000016E23287388>
<built-in method __format__ of student object at 0x0000016E23287388>
<class '__main__.student'>
<method-wrapper '__eq__' of student object at 0x0000016E23287388>
>>> 
Watch complete lecture 37:-

For More...

0 comments:

Post a comment

Powered by Blogger.