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.
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.