How to Define a Class Constructor in Python?

In Python, the responsibilities of a "constructor" are split over two methods:

  1. __new__() — it is a static method that's responsible for creating (and returning) a new instance of the class;
  2. __init__() — it is an instance method that's responsible for initializing the instance after it has been created (and does not return anything).

The __init__ method, however, is the closest to the definition of a conventional "constructor" as you would see in other OOP languages (such as C++, Java, PHP etc.). It has the following syntax:

class Contact:
    def __init__():
        # ...

You would create an instance of this class, for example, like so:

contact = Contact()

The first argument to the __init__() method is always the "self" variable (which is called "self" by convention, but can be named anything). It represents the instance of the object itself, and can be used to access/assign instance attributes:

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

contact = Contact('John Doe', 24)

print( # 'John Doe'
print(contact.age) # 24

In fact, whenever any instance method is called, a reference to the instantiated object is passed as the first argument to that method. For example, notice how the add_phone() method (in the code below) receives "self" as the first argument:

class Contact:
    def __init__(self, name, age): = name
        self.age = age = []

    def add_phone(self, number):

contact = Contact('John Doe', 24)

print( # ['+123456789', '+198765432']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.