Constructors in Python

 

Constructors in Python

 

Constructors:

Constructors are used to initialise the objects in class. When objects are created the constructors are used to assign the values to the data members of class. In Python __init__ function is the constructor it is automatically called when objects are created.

 

Syntax to create Constructors in Python

class class_name:

          statements

          def __init__(self):

          statements

A constructor in python is a method with always having name __init__. This is built-in function which is prefixed and suffixed with underscore(__). Constructor is declared with def keyword. 

Types of Constructors in Python:

Default Constructor:

The default constructor is a constructor which does not accept an argument. It have only one argument

For example,

# Demonstration of default constructor

class myname:

    #constructor function declaration

    def __init__(self):

        self.name="My name is Manisha"

    #Member function

    def display(self):

        print(self.name)

# Object creation

obj=myname()

# Function call

obj.display()

O/P:

My name is Manisha

 

Parameterised Constructors:

The constructors with one or more parameters is called parameterised constructor. Every parameterised constructor takes first argument as self a reference to the instance and other argument are given by user. 

# Demonstration of parameterised constructor

class sample:

    a=b=c=0

    def __init__(self,a,b):

        self.a=a

        self.b=b

    def result(self):

        print("The first number is",self.a)

        print("The second number is",self.b)

        self.c=self.a+self.b

        print("Sum of two numbers is",(self.c))

obj=sample(20,20)

obj.result()

        O/P:

The first number is 20

The second number is 20

Sum of two numbers is 40

 

 

टिप्पणी पोस्ट करा

0 टिप्पण्या