7.1.7 - Constructors

In the previous chapter we have created objects (instances of a class) and after the creation we added the fields as name, color, weight, etc.

This is not convenient and not completely correct because the time a new object is created is empty. To avoid it, we are using a constructor of an object inside the class definition.

Review the code below (www.pythontutor.com)

class Dog(): def __init__(self, new_name): """ Constructor. """ self.name = new_name print("A new dog is born. It's name is " + new_name + ".") my_dog=Dog("Spot")


The init function in this code has an argument except self. This is the self.name of the new object. Also inside the init we can print a message to be informed of the new object.

Copy the code that creates the class to Thonny script area and save it classConstructor.

At the CLI area try to create a new dog object with a name and without a name.

>>> my_dog = Dog("Pythos")

>>> my_dog = Dog()