1.__new__ and __init__
Name(...) actually runs two steps: __new__(cls, ...) creates and returns a fresh, empty object, then __init__(self, ...) sets up its attributes. __new__ is rarely overridden — almost all classes only ever touch __init__.
Key features
- Name(...) calls __new__ first to create the object, then __init__ to set it up
- __new__(cls, ...) is a staticmethod (implicitly) that must return an instance
- If __new__ returns an instance of cls, Python calls __init__ on it automatically
- __init__ never returns a value — returning anything but None is a TypeError
- Overriding __new__ is rare — mainly for immutable-type subclassing and singletons
The two-step construction pipeline
- __new__(cls) — creates a blank object
- __init__(self) — sets up its attributes
- Name(...) — returns the finished object
Command
class Name:
def __new__(cls, *args, **kwargs):
instance = super().__new__(cls) # actually allocate
return instance
def __init__(self, *args, **kwargs):
... # then set up attributesName(...) is two steps: __new__ creates the object, __init__ sets it up. Override __new__ only for singletons or immutable-type subclassing.