Back
+15 XP
Concept

Object Lifecycle: `__new__` vs `__init__`

`__new__` actually allocates and creates the object in memory and returns it. `__init__` merely customizes that newly created instance. Use `__new__` for Singletons.

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

a = Singleton()
b = Singleton()
print(a is b)  # True! Identical object in RAM!

# 10. Object Lifecycle: `__new__` vs `__init__` `__new__` actually allocates and creates the object in memory and returns it. `__init__` merely customizes that newly created instance. Use `__new__` for Singletons: ```python class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance a = Singleton() b = Singleton() print(a is b) # True! Identical object in RAM! ``` `__new__` is the true constructor, while `__init__` is an initializer. You almost never need to touch `__new__` unless you are writing singletons, customizing immutable built-in types (like `int` or `str`), or writing metaclasses.

Checkpoint

Which dunder method actually creates and returns the new instance in memory?

Practice

Implement a `Singleton` pattern using `__new__`. Verify `s1 = Singleton()` and `s2 = Singleton()` return the exact same instance using `print(s1 is s2)`.

Terminal
01
Tap code blocks below to assemble
Available Blocks