Constructors are special methods used to initialize objects when they are created from a class. Object creation and initialization are handled through the __new__() and __init__() methods. Constructors help assign initial values to object attributes and prepare objects for use.
When an object is created:
- The __new__() method creates and returns a new instance of the class.
- The __init__() method initializes the newly created object.
- The object becomes ready for use.
__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__.
Syntax:
class ClassName:
def __new__(cls, parameters):
instance = super(ClassName, cls).__new__(cls)
return instance
__new__() controls the actual creation of an object before __init__() initializes it. It is rarely needed in everyday Python programming, but it is useful when creating immutable objects, implementing singleton patterns, or controlling which instance gets created.
To learn more, please refer to this article: __new__
__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:
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 this article: __init__
__init__ vs __new__
| Feature | __new__() | __init__() |
|---|---|---|
| Purpose | Creates an object | Initializes an object |
| Called When | Before object creation completes | After object creation |
| Return Value | Must return an object instance | Returns None |
| Usage | Rarely overridden | Commonly overridden |
| Typical Use Case | Singleton, immutable objects | Setting attribute values |
Types of Constructors
1. Default Constructor: does not take any parameters other than self. It initializes the object with default attribute values.
class Car:
def __init__(self):
self.make = "Toyota"
self.model = "Corolla"
self.year = 2020
car = Car()
print(car.make)
print(car.model)
print(car.year)
Output
Toyota Corolla 2020
Note: If no constructor is defined in a class, Python automatically provides a default constructor that creates the object without initializing custom attributes.
Explanation:
- Define Constructor: __init__() is defined without additional parameters.
- Initialize Attributes: Default values are assigned to make, model, and year.
- Create Object: Car() automatically invokes the constructor.
- Access Attributes: Object attributes are printed using dot notation.
2. Parameterized Constructor: accepts arguments to initialize the object's attributes with specific values.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
car = Car("Honda", "Civic", 2022)
print(car.make)
print(car.model)
print(car.year)
Output
Honda Civic 2022
Explanation:
- Accept Parameters: The constructor receives make, model, and year as arguments.
- Assign Values: Constructor arguments are assigned to instance attributes.
- Create Object: Values are passed while creating the object.
- Display Attributes: The stored values are accessed through the object.