Python Reference ยท Classes and Special Methods
__init__() and __new__()
Reference for Python __init__() and __new__(): how instances are created and initialized, calling super, immutable subclasses and the singleton pattern.
Creating an object in Python takes two steps. __new__() builds the bare instance, and __init__() then fills it with data. When you write Point(1, 2), Python calls Point.__new__(Point, 1, 2) and, if that returns an instance of Point, calls __init__() on it with the same arguments.
Almost every class defines only __init__(), which sets the initial attributes. You need __new__() rarely: for immutable types such as int, str and tuple, for singletons and for caching instances.
class Point: def __init__(self, x, y): self.x = x self.y = y
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
class C: def __new__(cls, *args, **kwargs): instance = super().__new__(cls) return instance def __init__(self, *args, **kwargs): ...
| Method | Description |
|---|---|
__new__(cls, ...) |
A static method (implicit) that receives the class and returns the new instance. |
__init__(self, ...) |
Receives the new instance and initializes it. |
Return value: __new__() returns the instance (or any object). __init__() must return None.
Raises: TypeError if __init__() returns anything but None, or when the call's arguments do not match the signature.
Usage notes
__init__does not create anything. It only sets up an object that already exists. That is why it returnsNone.- If
__new__returns something that is not an instance of the class,__init__()is skipped, as theOtherexample shows. - Call the parent's initializer with
super().__init__(...)in subclasses. Forgetting it leaves the parent's attributes unset. - Immutable types need
__new__. By the time__init__()runs on anintorstrsubclass, the value is already fixed. - Every
Config()call still runs__init__on the shared singleton instance, so keep singleton initialization idempotent. - Don't forward extra arguments to
object.__new__. When a class overrides__new__(),object.__new__(cls, *args)raisesTypeErrorfor surplus arguments, so callsuper().__new__(cls)with the class only (as in the examples). Subclasses ofint,strortuplepass their value on instead. - Prefer alternatives. Default values and class methods such as
from_dict()replace most overloaded constructors;@dataclassgenerates__init__()for plain data classes. - Do not do heavy work such as network calls in
__init__; it makes classes hard to test.
Related
object,super(),__str__() and __repr__(),classmethod()- Lessons: Classes, Inheritance, Data classes