DeployU
Interviews / Backend Engineering / What is the difference between `__init__` and `__new__` in Python?

What is the difference between `__init__` and `__new__` in Python?

conceptual Object-Oriented Programming Interactive Quiz Code Examples

The Scenario

You are a backend engineer at a fintech company. You are writing a new class that needs to have some custom logic for creating new instances of the class.

You are not sure whether to put this logic in the __init__ method or the __new__ method.

The Challenge

Explain the difference between the __init__ and __new__ methods in Python. When would you use one over the other?

Wrong Approach

A junior engineer might not be aware of the `__new__` method. They might try to put the instance creation logic in the `__init__` method, which would not work.

Right Approach

A senior engineer would know that `__new__` is used to create new instances of a class, while `__init__` is used to initialize new instances of a class. They would be able to explain the difference between the two methods and would have a clear plan for how to use them to solve this problem.

Step 1: Understand the Key Differences

MethodPurpose
__new__To create a new instance of a class.
__init__To initialize a new instance of a class.

The __new__ method is called before the __init__ method. It is responsible for creating a new instance of the class and returning it. The __init__ method is then called on the new instance to initialize it.

Step 2: When to use __new__

You would use the __new__ method when you need to customize the instance creation process. For example, you might use it to:

  • Implement the singleton pattern.
  • Create a subclass of an immutable type, like str or int.
  • Implement a custom metaclass.

Step 3: Code Examples

Here is an example of how to use the __new__ method to implement the singleton pattern:

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = Singleton()

print(s1 is s2) # True

In this example, the __new__ method checks if an instance of the class already exists. If it does, it returns the existing instance. If it does not, it creates a new instance and returns it.

Practice Question

You want to create a new class that inherits from `str` and has some custom behavior. Which method would you use to customize the instance creation process?