Python

Constructor

A constructor is the first method that is called on object creation.

The constructor is always called when creating a new object.
It can be used to initialize class variables and startup routines.

Related course: Python Beyond the Basics – Object-Oriented Programming

Example

In the example below we create a class C with a constructor and the method see. \

We create one object C. On execution it will output both lines because we call the method and when creating the object it calls the constructor.

In Python a constructor is written as init(self)

class C:
def __init__(self):
print('Constructor called.')

def see(self):
print('C')

obj = C()
obj.see()

This will output:

Constructor called.
C

Watch how the output of the constructor is shown first.

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP