A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/constructors-in-python/ below:

Constructors in Python - GeeksforGeeks

Constructors in Python

Last Updated : 11 Jul, 2025

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)


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4