Meaning
The __new__ method is a static method that creates and returns a new class object. It receives the metaclass (cls), the class name, base classes, and namespace dictionary, and is responsible for object creation before __init__ is called.
Primary Function
Create and return a new class object.
Communicative Purpose
Defines the class creation protocol, allowing customization of how classes are constructed.
Pattern
def __new__(cls, name, bases, dct):
Core Structure
def __new__(cls, name, bases, dct):
Função primária
Create and return a new class object.
Propósito comunicativo
Defines the class creation protocol, allowing customization of how classes are constructed.
Situações de gatilho
When defining a custom metaclass to modify class creation, enforce patterns (e.g., singletons), inject attributes, or control subclassing behavior.
Contextos
Inside a class statement that defines a metaclass, or when using type() dynamically to create classes.
Padrão
def __new__(cls, name, bases, dct):
Estrutura central
def __new__(cls, name, bases, dct):
Slots de substituição
cls: the metaclass; name: class name string; bases: tuple of base classes; dct: dictionary of class attributes.
Colocados típicos
- __init__
- metaclass
- super()
- type
Substituições comuns
- __init__ (for instance initialization)
- __init_subclass__ (for subclass hook)
Erros comuns
Forgetting to return the new class object; mishandling the namespace dict; confusing __new__ with __init__.
Similar / contraste
__init__ (initializes instances after creation), __init_subclass__ (hook called when a class is subclassed), __metaclass__ (deprecated way to specify metaclass).
Interferências
Confusing __new__ with __init__ can lead to partially initialized classes; returning an incorrect type breaks class creation.
Família do chunk
- __init__
- __metaclass__
- metaclass
- __init_subclass__
Nuance
__new__ must return a class object (usually via super().__new__); returning None prevents class creation and suppresses __init__.
Efeito pragmático
Enables customization of class creation, supporting patterns such as singletons, automatic registration, attribute injection, and domain-specific metaclasses.
Dica de memória
Think of __new__ as the class factory method.
Nota
__new__ is implicitly a static method; an explicit @classmethod decorator is optional but common.
Log in to save chunks.