Constructors in Python (original) (raw)

Last Updated : 20 Nov, 2024

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:

__init__ method:

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)

`