Python – Part #4 (Classes, Constructors & Objects)

One of the key concepts in object-oriented programming is the idea of classes, constructors, and objects.

A class in Python is a blueprint or a template for creating objects that share a common structure and behavior. It defines a set of attributes (variables) and methods (functions) that the objects of that class will have.

Constructors are special methods in a class that are used to initialize the attributes of an object when it is created. The constructor method is called automatically when an object of the class is created, and it can take arguments that are used to set the initial values of the object’s attributes.

An object (also called an instance) is a specific instance of a class. It has its own set of attributes and methods that are defined by the class, but the values of those attributes can be different for each object.

In Python, you define the class by using the class keyword followed by the name of the class (I personally use Pascal convention for naming classes) and a colon. The class definition typically includes a constructor method that is defined with the special name __init__. Here’s an example of a simple Python class using a constructor:

In this example, we define a Car class that has three attributes (make, model, and year) and one method (drive). The constructor method takes three arguments (make, model, and year) and initializes the corresponding attributes of the object using the self keyword.

The self keyword is just taking the variable and storing what is passed to itself.

To create an instance of the Car class, we can call the constructor method using the class name and provide the necessary arguments:

This creates a new object (instance) of the Car class names my_car with the make attribute set to “Toyota”, the model attribute set to “Camry”, and the year attribute set to 2022.

We can then call the drive method on the my_car object:

This will print out the message “Toyota Camry is driving.” since the drive method is defined to print out that message.

In conclusion as you could see the concept of Classes, constructors and objects is pretty straightforward, these are mainly used to reduce repetition of code and to make it reusable, It’s essential to learn this as it would get more complex when learning related topics such as inheritance.