The perfect place for easy learning...

Python

×

Topics List


Python Constructor





The Python is an object-oriented programming language from its beginning. Almost everything in Python implemented using object concept. The Python support all the features of OOP.

In Python, the class may contain data members, member functions (methods), and Python statements. Every class in Python has a special method __init__( ) which executes on every object creation of that class.

A constructor is a special method or member function of a class which automatically gets executes on every object creation.

There are two types of constructors and they are as follows.

  • Constructor without parameters (or) Default Constructor
  • Constructor with parameters (or) Parameterized Constructor

Default Constructor is a constructor without any parameters, however, it has a default parameter self.

Parameterized Constructor is a constructor with one or more parameters. A parameterized constructor may have any number of parameters.

Creating Default Constructor

In Python, the constructor is created using a special method called __init__( ). In programming languages like C++, Java, etc. the constructor has the same name as the class name, but in Python, every class has the constructor with same name __init__( ).

Example
class Sample:
    i = 10
    def __init__(self):
        self.i = 100
        print(f'Object has created!')
        print(f'Data member "i" is initialized with {self.i}.')

obj = Sample()

When we run the above example code, it produces the following output.

Python Class constructor

When the user does not define any constructor, the compiler automatically creates a default constructor.


In Python, a class can have only one constructor. Constructor overloading is not allowed in Python.


Creating Parameterized Constructor

In Python, a constructor may have any number of parameters. The following code illustrates how parameterized constructor is created.

Example
class Sample:
    i = 10
    def __init__(self, value):
        self.i = value
        print(f'Object has created!')
        print(f'Data member "i" is initialized with {self.i}.')

obj = Sample(1000)

When we run the above example code, it produces the following output.

Python Constructor

Points to be Remembered!
  • In Python, the method __init__( ) is called as constructor but it does not creates an object instead it instatiates the object. To create an object, Python uses a special method __new__( ). When a class has both __init__( ) and __new__( ) methods, the __new__( ) method overrides __init__( ) method.
  • In Python, actually both __new__( ) and __init__( ) together forms a constructor.
  • The __new__( ) method is used to create an object.
  • The __init__( ) method is used to instantiate an object.

Your ads here