A constructor is the first method that is called on object creation (a concept from Object Orientated Programming). It is always part of a class (an objects methods are defined in a class).

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

Related course: Python Programming Courses & Exercises

Introduction

A constructor is a method inside the class, that is called if a new object is created.

The constructor allows you to set variables for the object immediately.

user[1] = User('Alice','Coder','Windows')
user[2] = User('Bea','Marketeer','Mac')

Instead of having to set each variable manually like

user[1].name = 'Alice'
user[1].job = 'Coder'
user[1]....
# etc

Each class can contain one and only one constructor.

The constructor is always named def __init__(self):.

The image below shows two classes, with one constructor each (highlighted).

python constructor

There are a few rules for constructors:

  • A constructor must be defined with the name __init__.
  • A constructor must be defined with the self keyword in its parameters.
  • A constructor cannot return any value, except None.
  • Only one constructor is allowed for a class.
  • Only for object initialization

Example

The syntax of a constructor is def __init__(self):. Inside a class it looks like this:

class Example:
def __init__(self):
pass

If you then create an example, the constructor will be called. If you create two objects, the constructor will be called twice.

obj1 = Example() # constructor called
obj2 = Example() # constructor called

The idea of the constructor is to set object variables.

You could have a class like this:

>>> class Computer:
... def __init__(self, name, speed):
... self.name = name
... self.speed = speed
...

Then create a few objects.

Each object has unique values, just like the real world.

Those values are set when creating the object, this is where the constructor is called in the background.

>>> apple = Computer('Apple',100)
>>> iphone = Computer('Apple iOS', 10)
>>> watch = Computer('Watch', 1)

If you are a Python beginner, then I highly recommend this book.

Visual example

In the example below we create a class C with a constructor and the method see. In Python a constructor is named init.

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

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

The constructor (init) is just another method. What is special about it, is that its called each time a new object is created.

We create one object C with the line:

obj = C()

constructor

On execution it will output both lines of text. Why? because we call the method and when creating the object it calls the constructor.

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.

The constructor is called immediately when creating objects, this is especially clear in the Python shell.

If this is your class:

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

Then it calls the constructor for each object created:

>>> obj1 = C()
Constructor called
>>> obj2 = C()
Constructor called
>>> obj3 = C()
Constructor called
>>>

Real world example

In a real world scenario, the constructor does useful things for the newly created object. In example, a constructor fo the Car. It sets the default values of variables like number of wheels, number of doors.

If you define a class Car, which sets some of the objects variables (note self is used to refer to the objects values), it gets set on creation.

>>> class Car:
... def __init__(self):
... self.wheels = 4
... self.doors = 2
... self.chairs = 2
...

Then if you create some objects and request objects variables to be shown, they are already set (because we set them in the constructor.

>>> obj1 = Car()
>>> obj2 = Car()
>>> print(obj1.doors)
2
>>> print(obj2.doors)
2
>>> print(obj2.wheels)
4
>>>

Types of constructors

There are two types of constructors in Python.

The default constructor, which doesn’t have any arguments.

class myClass:
def __init__(self):
...

And the parameterized constructor, this takes one or more arguments.

class myClass:
def __init__(self,x,y,w,h):
...

Why would you want a default constructor, instead of just leaving it out?

Because you can call some initialization functions from there.

Something like this:

class Telsa:
def __init__(self):
lights(on)
engine(on)
gps(on)
...

whereas if you leave it out, no methods can be called and no parameters can be set on creation.

class Telsa:
pass

You can also set variables in the default constructor,

class Tesla:
def __init__(self):
self.wheels = 4
self.lights = 4

If you are a Python beginner, then I highly recommend this book.

Download exercises