Object-oriented programming · 3 / 26 Theory

Constructors

A constructor is the special method that runs automatically when an object is created, and it is used to give its attributes their initial values. In Python the constructor is called __init__.

The __init__ method

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

ana = Person("Ana", 30)
print(ana.name, ana.age)   # Ana 30

When you write Person("Ana", 30), Python creates the object and calls __init__ passing the object as self followed by your arguments.

Default values

A parameter can have a default value, so it becomes optional:

class Person:
    def __init__(self, name, age=18):
        self.name = name
        self.age = age

print(Person("Leo").age)       # 18
print(Person("Leo", 40).age)   # 40

There is no constructor overloading

In Python a class has a single __init__. To offer different ways of creating objects you use default values or class methods:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_text(cls, text):
        name, age = text.split(",")
        return cls(name, int(age))

p = Person.from_text("Mia,22")
print(p.name, p.age)   # Mia 22

Constructors and inheritance

A child class calls the constructor of the parent class with super():

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

Destructor

The special method __del__ is called when an object is about to be removed from memory. It is rarely needed, because Python frees the memory automatically.