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
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:
Inside the constructor we initialize two variables: legs and arms. We create one object (bob) and just by creating it, its variables are initialized.
The constructor of a class is unique: initiating objects from different classes will call different constructors.
But creating multiple objects from one class, will call the same constructor.
Try the exercise below:
- Make two additional objects
- Add another variable and initialize it