Link Search Menu Expand Document

Create your constructor

When you use () with the class, such as Person(), you are using the constructor. The constructor allows you to create an object of a given class. Thus, an object of class Person is constructed.

class Person:
    pass
p = Person()

But in this class, we have not defined the constructor. Let us define it.

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

Now that the constructor accepts three arguments, we can construct our object as follows.

p = Person("Ana", "Ruiz", 20)

We can also construct the object like this.

p = Person(
    first_name="Ana",
    last_name="Ruiz",
    age=20)

The constructor, like any function, can have default arguments. These will be used if no such argument is provided.

class Person:
    def __init__(self, first_name='', last_name='', age=0):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

In this case, since we do not provide age, the default value 0 is used.

p = Person("Ana", "Ruiz")
print(p.first_name) # Ana
print(p.age)        # 0

The __init__ constructor is also useful to verify that the arguments with which we construct the object are correct. In this case, we verify that the age is not negative.

class Person:
    def __init__(self, first_name, last_name, age):
        if age < 0:
            raise Exception("Age cannot be negative.")
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

p = Person("Ana", "Ruiz", -10)
# Exception: Age cannot be negative.

Although this is not the recommended way to do it, Python allows you to create an object as follows. It is interesting to understand how it works and how it is done internally, but do not do it that way. Use the way we have seen above.

# It works, but do not use it.
person = Person.__new__(Person)
Person.__init__(person, "Ana", "Ruiz", 20)

You could say that Python internally converts everything inside () and passes it to the function. But do not do it that way.