Middle
What is the difference between the __init__ and __new__ methods in Python?
sobes.tech AI
Answer from AI
__new__ — a static method (implicitly receives the class cls as the first argument, not the instance self) responsible for creating an instance of an object. It is called before __init__. If __new__ returns an instance of the class it was called on (or its subclass), then the __init__ method is called to initialize this instance. If __new__ returns an instance of another class, __init__ is not called.
__init__ — an instance method (receives the instance self as the first argument), responsible for initializing (setting up) an already created object instance.
Use of __new__ is usually required in the following cases:
- Changing behavior when creating instances of immutable types (strings, numbers, tuples).
- Implementing patterns such as Singleton.
- Inheriting from immutable built-in types.
Example of using __new__ to implement Singleton:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls) # Call __new__ of the base class to create an instance
return cls._instance
def __init__(self, value):
# __init__ will be called every time if __new__ returns the same instance
self.value = value
# Creating instances
s1 = Singleton(1)
s2 = Singleton(2)
# Check that these are the same instance
# print(s1 is s2) # Output: True
# print(s1.value) # Output: 2
# print(s2.value) # Output: 2
Example of using __init__:
class MyClass:
def __init__(self, name):
self.name = name # Initialize the attribute
def greet(self):
return f"Hello, {self.name}!"
# Creating an instance and calling a method
# obj = MyClass("World")
# print(obj.greet()) # Output: Hello, World!
Comparison:
| Method | Purpose | Method Type | First Argument | When Called | Typical Use Cases |
|---|---|---|---|---|---|
__new__ |
Creating an instance | Static | cls (class) |
Before __init__ |
Overriding creation of immutable type instances, Singleton, inheriting from immutable built-in types |
__init__ |
Initializing an instance | Instance | self (instance) |
After __new__ (if __new__ returned an instance of the class) |
Setting up the created instance, assigning attribute values |