Open In App

Constructors in Python

Last Updated : 20 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state.

The method __new__ is the constructor that creates a new instance of the class while __init__ is the initializer that sets up the instance’s attributes after creation. These methods work together to manage object creation and initialization.

__new__ Method

This method is responsible for creating a new instance of a class. It allocates memory and returns the new object. It is called before __init__.

Python
class ClassName:
    def __new__(cls, parameters):
        instance = super(ClassName, cls).__new__(cls)
        return instance

To learn more, please refer to “__new__ ” method

__init__ Method

This method initializes the newly created instance and is commonly used as a constructor in Python. It is called immediately after the object is created by __new__ method and is responsible for initializing attributes of the instance.

Syntax:

Python
class ClassName:
    def __init__(self, parameters):
        self.attribute = value

Note: It is called after __new__ and does not return anything (it returns None by default).

To learn more, please refer to “__init__” method

Differences Between __init__ and __new__

__new__ method:

  • Responsible for creating a new instance of the class.
  • Rarely overridden but useful for customizing object creation and especially in singleton or immutable objects.

__init__ method:

  • Called immediately after __new__.
  • Used to initialize the created object.

Types of Constructors

Constructors can be of two types.

1. Default Constructor

A default constructor does not take any parameters other than self. It initializes the object with default attribute values.

Python
class Car:
    def __init__(self):

        #Initialize the Car with default attributes
        self.make = "Toyota"
        self.model = "Corolla"
        self.year = 2020

# Creating an instance using the default constructor
car = Car()
print(car.make)
print(car.model)
print(car.year)

Output
Toyota
Corolla
2020

2. Parameterized Constructor

A parameterized constructor accepts arguments to initialize the object’s attributes with specific values.

Python
class Car:
    def __init__(self, make, model, year):
      
        #Initialize the Car with specific attributes.
        self.make = make
        self.model = model
        self.year = year

# Creating an instance using the parameterized constructor
car = Car("Honda", "Civic", 2022)
print(car.make)
print(car.model)
print(car.year)

Output
Honda
Civic
2022


Next Article
Article Tags :
Practice Tags :

Similar Reads