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-Paparameterized Constructor (Default Constructor)

Non-Paparameterized 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:

#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:

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:
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
>>> 

Visitor Counter

0051170