Python Class Constructor


Python Class Constructor

A class constructor is called during object creating, and is used to initialize the class instance (object).

In Python, __init__() function defined in the class is the constructor.

For example, take the following class Person.

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

When an object of type Person is created, say Person('Mike', 21), the method __init__() receives two arguments 'Mike', 21 for initialising the object.

The first argument 'Mike' is assigned to the parameter name.

The second argument 21 is assigned to the parameter age.

You will learn more about the self parameter present in the __init__() definition, in this tutorial: self parameter in class.