❮ Previous Next ❯

Python Constructor


A constructor is a special type of method (function)specifically used to initialize the instance members of the class.

Constructor can be parameterized and non-parameterized as well.

When we create object of a class, if the program containing Constructor, then it executes automatically.

If a program having no constructor, Python creates a default constructor automatically that does not do anything.

Constructors also verify that there are enough resources for the object to perform any start-up task.

Creating a Constructor


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

Every class must have a constructor, even if it simply relies on the default constructor.

There are 2 types of constructors like non-parameterized and parameterized constructor.

0-arg Constructor

Example1.py

class Abcd:
  x=0
  y=0;
  def __init__(self):   #0-arg constructor
    self.x=100
    self.y=200
  def show(self):
     print("x=",self.x)
     print("y=",self.y)

obj=Abcd()
obj.show()


OUTPUT
x= 100
y= 200

Python Non Parameterized Constructor Example


The constructor taking no parameter is known as non-parameterized constructor. Let's see an example for better understanding:

Example:

python constructor1

Python Parameterized Constructor Example


The constructor taking parameter is known as parameterized constructor. Let’s see an example:

python constructor2

❮ Previous Next ❯

Follow Us




  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved