The constructor is a method that is called when an object is created. This method is defined in the class and can be used to initialize basic variables.

If you create four objects, the class constructor is called four times. Every class has a constructor, but its not required to explicitly define it.

Related course: Complete Python Bootcamp: Go from zero to hero in Python

Example

The constructor is created with the function init. As parameter we write the self keyword, which refers to itself (the object). The process visually is:

constructor

Inside the constructor we initialize two variables: legs and arms. We create one object (bob) and just by creating it, its variables are initialized.

class Human:
def __init__(self):
self.legs = 2
self.arms = 2

bob = Human()
print(bob.legs)

The constructor of a class is unique: initiating objects from different classes will call different constructors.

class Bug:
def __init__(self):
self.wings = 4

class Human:
def __init__(self):
self.legs = 2
self.arms = 2

bob = Human()
tom = Bug()

print(tom.wings)
print(bob.arms)

But creating multiple objects from one class, will call the same constructor.

Exercise

Try the exercise below:

  1. Make two additional objects
  2. Add another variable and initialize it

Download answers