Python OOPs Concepts 6

Python Constructors

A constructor is a special method (function) which if present automatically gets invoked as an object of the class is declared.

It is generally used to initialize the instance members of the class. Constructors can be of two types.

* non-parameterized
* parameterized

A constructor function begins with double underscore (_). The name of the constructor is always the same __init__().

 

Non-Parameterized Constructor (Default Constructor)

Non-Parameterized Constructor or Default Constructor are the constructors which if present automatically gets executed when an object of a class is declared without any parameters.

example:
if  student is a class then
s=student()
will invoke the default constructor

Example:1

#class creation
class sample:
    def __init__(self):
        print("This is default cons")
    def show(self):
        print("This is show function")
        

s=sample()
s.show()

Output:

This is default cons
This is show function
>>> 

Example:2
Python program to initialize the data elements of the class student using the default constructor and display them?

#class creation
class student:
    #default constructor
    def __init__(self): 
        self.roll=500
        self.name="Kishan"
        self.per=98.78
    def show(self):
        print("Roll no ",self.roll)
        print("Name ",self.name)
        print("Per ",self.per)
        
#calling
s=student()
s.show()

Output:

Roll no  500
Name  Kishan
Per  98.78
>>> 

Example:3
Python program to initialize the data elements of the class employee using the default constructor and display them?

#class creation
class employee:
    #default constructor
    def __init__(self): 
        self.empno=1001
        self.name="Mohan"
        self.sal=5700
    def show(self):
        print("Empno ",self.empno)
        print("Name ",self.name)
        print("Salary ",self.sal)
        

#calling
e=employee()
e.show()

Output:

Empno  1001
Name  Mohan
Salary  5700
>>> 

Example:4
Python program to initialize the data elements of the class product using the default constructor and display the details along with total cost?

#class creation
class product:
    #default constructor
    def __init__(self): 
        self.pno=1001
        self.pname="Surf"
        self.rate=50
        self.qty=5
        self.cost=0
    def cal(self):
        self.cost=self.rate*self.qty
    def show(self):
        self.cal()
        print("Pno ",self.pno)
        print("PName ",self.pname)
        print("Rate ",self.rate)
        print("Quantity ",self.qty)
        print("Total Cost ",self.cost)
        

#calling
p=product()
p.show()

Output:

Pno 1001
PName Surf
Rate 50
Quantity 5
Total Cost 250

Visitor Counter

0183300