Python Constructors

When creating an object from a class, it looks like we are calling a function:

car = Car()

Well... it doesn't just look like we are calling a function, we are in fact calling a function! This method, that we did not have to define, is called the constructor. It constructs and initializes the object. Every class has one by default, called __init__, even if we don't define it ourselves. This has to do with inheritance, which you'll learn about shortly.

Have you ever used the str() function to convert an object into a class? Or perhaps the int() function to convert a string into a number? 

>>> 'a' + str(1)
'a1'
>>> int('2') + 2
4

What you are actually doing here, is creating new objects of type str and int by calling the constructors of the classes str and int.

We can override the __init__ method too, to give it extra abilities by accepting arguments. Let's redefine the Car class using a custom constructor:

class Car:
    def __init__(self, started = False, speed = 0):
        self.started = started
        self.speed = speed

    def start(self):
        self.started = True
        print("Car started, let's ride!")

    def increase_speed(self, delta):
        if self.started:
            self.speed = self.speed + delta
            print("Vrooooom!")
        else:
            print("You need to start the car first")

    def stop(self):
        self.speed = 0

Our custom constructor has named parameters with default values, so we can create instances of class Car in multiple ways:

>>> c1 = Car()
>>> c2 = Car(True)
>>> c3 = Car(True, 50)
>>> c4 = Car(started=True, speed=40)

You may have noticed that we can now create a new car that is not started but give it a speed anyway. For now, let's just leave it at that.


If you liked this page, please share it with a fellow learner: