3.3 Special method names The Python Language Reference, Release 3.9.5 A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or sub- scripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading , allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named$_{__getitem__()}$ , and$_{x}$is an instance of this class, then$_{x[i]}$ is roughly equivalent to$_{type(x).}$ __getitem__(x, i) . Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError ). Setting a special method to None indicates that the corresponding operation is not available. For example, if a class sets __iter__() to None , the class is not iterable, so calling iter() on its instances will raise a TypeError (without falling back to$_{__getitem__()}$ ). 2 When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the$_{NodeList}$ interface in the W3C’s Document Object Model.) If$_{__new__()}$ does not return an instance of cls , then the new instance’s$_{__init__()}$ method will not be invoked. If$_{__new__()}$ is invoked during object construction and it returns an instance or subclass of cls , then the new instance’s$_{__init__()}$ method will be invoked like$_{__init__(self[, ...])}$ , where self is the new instance and the remaining arguments are the same as were passed to the object constructor. Typical implementations create a new instance of the class by invoking the superclass’s$_{__new__()}$ method using super().__new__(cls[, ...]) with appropriate arguments and then modifying the newly- created instance as necessary before returning it. Called to create a new instance of class cls . __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls ). __new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation. Called after the instance has been created (by$_{__new__()}$ ), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an$_{__init__()}$ method, the derived class’s$_{__init__()}$ method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example:$_{super().__init__([args...])}$ . Because$_{__new__()}$ and$_{__init__()}$ work together in constructing objects ($_{__new__()}$ to create it, and$_{__init__()}$ to customize it), no non-$_{None}$ value may be returned by$_{__init__()}$ ; doing so will cause a$_{TypeError}$ to be raised at runtime. Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor. If a base class has a$_{__del__()}$ method, the derived class’s$_{__del__()}$ method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. It is possible (though not recommended!) for the$_{__del__()}$ method to postpone destruction of the instance by creating a new reference to it. This is called object resurrection . It is implementation-dependent whether __del__() is called a second time when a resurrected object is about to be destroyed; the current CPython implementation only calls it once. 2 The __hash__() , __iter__() , __reversed__() , and __contains__() methods have special handling for this; others will still raise a TypeError , but may do so by relying on the behavior that None is not callable. object. __del__ ( self$_{)}$ object. __init__ ( self [, ... ] ) object. __new__ ( cls [, ... ] ) 3.3.1 Basic customization Chapter 3. Data model 26