__new__ vs __init__ in Python

As a Python developer, working on a project for USA clients I came across two special methods __new__ and __init__. We will get into the specifics of __new__ and __init__, providing detailed explanations and examples to illustrate their use.

__new__ and __init__ in Python

In Python, object-oriented programming (OOP) revolves around classes and objects. When creating an object, Python uses two methods: __new__ and __init__. Understanding these methods helps in customizing object creation and initialization, leading to more efficient and readable code.

Read How to Use the insert() Function in Python?

__new__ in Python

The __new__ method in Python is a static method responsible for creating a new instance of a class. It is the first step in object creation and is called before __init__. The __new__ method takes the class itself as its first argument, followed by any additional arguments passed to the class constructor.

Syntax

class MyClass:
    def __new__(cls, *args, **kwargs):
        instance = super(MyClass, cls).__new__(cls)
        return instance

Explanation

  • cls: The class being instantiated.
  • *args and **kwargs: Any positional and keyword arguments.

The __new__ method returns a new instance of the class. If __new__ does not return an instance of cls, the __init__ method will not be called.

__init__ in Python

The __init__ method is an initializer method that sets up the initial state of an object. It is called after the object is created and takes the instance (self) as its first argument, followed by any additional arguments passed to the class constructor.

Syntax

class MyClass:
    def __init__(self, *args, **kwargs):
        self.attribute = args[0] if args else None

Check out How to Use the arange() Function in Python?

Explanation

  • self: The instance being initialized.
  • *args and **kwargs: Any positional and keyword arguments.

The __init__ method does not return a value; it simply initializes the instance attributes.

Key Differences Between __new__ and __init__ in Python

Feature__new____init__
PurposeCreates a new instance of the classInitializes the instance
Method TypeStatic methodInstance method
ArgumentsTakes the class itself as the first argument (cls)Takes the instance itself as the first argument (self)
Return ValueMust return a new instance of the classDoes not return a value
Called WhenCalled before __init__Called after __new__
Use CaseCustomizing instance creation, especially for immutable typesSetting initial state of the instance

Read How to Use the Python Pass Function?

Usage of __new__ in Python

The __new__ method is particularly useful in the following scenarios:

  1. Immutable Types: For creating instances of immutable types like tuples, strings, or numbers.
  2. Singleton Pattern: Ensuring a class has only one instance.
  3. Metaclasses: Customizing class creation.

Example: Create a Singleton

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def __init__(self, value):
        self.value = value

a = Singleton(10)
b = Singleton(20)
print(a.value)
print(b.value) 
print(a is b)   

Output:

20
20
True

I have executed the above code and added the screenshot below.

__new__ vs __init__ in Python

Check out How to Use the trim() Function in Python?

Usage of __init__ in Python

The __init__ method is used for:

  1. Setting Initial State: Initializing instance attributes.
  2. Dependency Injection: Passing dependencies to the instance.
  3. Validation: Validating input parameters.

Example: Initialize Attributes

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

    def __str__(self):
        return f'{self.name}, {self.age} years old'

p = Person('Alice', 30)
print(p)  # Output: Alice, 30 years old

Output:

Alice, 30 years old

I have executed the above code and added the screenshot below.

__new__ vs __init__ in Python Initialize Attributes

Read How to Use the strip() Function in Python?

Examples

Let us work on some examples to understand more about __new__ and __init__.

Example 1: Custom Object Creation

class CustomClass:
    def __new__(cls, *args, **kwargs):
        instance = super(CustomClass, cls).__new__(cls)
        instance.custom_attr = 'Custom Attribute'
        return instance

    def __init__(self, name):
        self.name = name

obj = CustomClass('Example')
print(obj.name)       
print(obj.custom_attr)

Output:

Example
Custom Attribute

I have executed the above code and added the screenshot below.

__new__ vs __init__ in Python Custom Object Creation

Check out How to Implement and Use the hash() Functions in Python?

Example 2: Immutable Object Creation

class ImmutablePoint:
    def __new__(cls, x, y):
        instance = super(ImmutablePoint, cls).__new__(cls)
        instance.x = x
        instance.y = y
        return instance

    def __init__(self, x, y):
        pass  # Initialization already done in __new__

point = ImmutablePoint(1, 2)
print(point.x, point.y)

Output:

1  2

Summary

Feature__new____init__
PurposeCreates a new instance of the classInitializes the instance
Method TypeStatic methodInstance method
ArgumentsTakes the class itself as the first argument (cls)Takes the instance itself as the first argument (self)
Return ValueMust return a new instance of the classDoes not return a value
Called WhenCalled before __init__Called after __new__
Use CaseCustomizing instance creation, especially for immutable typesSetting initial state of the instance

Read How to Use the map() Function in Python?

Conclusion

In this tutorial, we learned the difference between __new__ and __init__ in Python. I discussed syntax and explanation of both __new__ and __init__, the key difference between __new__ and __init__, and usage of both __new__ and __init__ with examples. I also discussed customer objects , immutable object creation and summary.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.