| Python Language Reference Manual by Guido van Rossum and Fred L. Drake, Jr. Paperback (6"x9"), 120 pages ISBN 0954161785 RRP £12.95 ($19.95) Sales of this book support the Python Software Foundation! Get a printed copy>>> |
3.4.1 Basic customization
__new__(cls[, ...])-
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). Typical implementations create a new instance of the class by invoking the superclass's__new__()method using ‘super(currentclass, cls).__new__(cls[, ...])’ with appropriate arguments and then modifying the newly-created instance as necessary before returning it. If__new__()returns an instance 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__new__(). If__new__()does not return an instance of cls, then the new instance's__init__()method will not be invoked.__new__()is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation.
__init__(self[, ...])-
Called when the instance is created. 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: ‘BaseClass.__init__(self, [args...])’. As a special constraint on constructors, no value may be returned; doing so will cause aTypeErrorto be raised at runtime.
__del__(self)-
Called when the instance is about to be destroyed. This is also
called 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. Note that it is possible (though not recommended!) for the__del__()method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that__del__()methods are called for objects that still exist when the interpreter exits. Notice: ‘del x’ doesn't directly callx.__del__()---the former decrements the reference count forxby one, and the latter is only called whenx's reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored insys.exc_tracebackkeeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored insys.last_tracebackkeeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the latter two situations can be resolved by storingNoneinsys.exc_tracebackorsys.last_traceback. Circular references which are garbage are detected when the optional cycle detector is enabled (it's on by default), but can only be cleaned up if there are no Python-level__del__()methods involved. Refer to the documentation for the ‘gc’ module for more information about how__del__()methods are handled by the cycle detector, particularly the description of thegarbagevalue. Notice: [warning] Due to the precarious circumstances under which__del__()methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed tosys.stderrinstead. Also, when__del__()is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the__del__()method may already have been deleted. For this reason,__del__()methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the__del__()method is called.
__repr__(self)-
Called by the
repr()built-in function and by string conversions (reverse quotes) to compute the "official" string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form ‘<...some useful description...>’ should be returned. The return value must be a string object. If a class defines__repr__()but not__str__(), then__repr__()is also used when an "informal" string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
__str__(self)-
Called by the
str()built-in function and by theprintstatement to compute the "informal" string representation of an object. This differs from__repr__()in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.
__lt__(self, other)__le__(self, other)__eq__(self, other)__ne__(self, other)__gt__(self, other)__ge__(self, other)-
Added in version 2.1, these are the so-called "rich comparison" methods, and are called
for comparison operators in preference to
__cmp__()below. The correspondence between operator symbols and method names is as follows:x<ycallsx.__lt__(y),x<=ycallsx.__le__(y),x==ycallsx.__eq__(y),x!=yandx<>ycallx.__ne__(y),x>ycallsx.__gt__(y), andx>=ycallsx.__ge__(y). These methods can return any value, but if the comparison operator is used in a Boolean context, the return value should be interpretable as a Boolean value, else aTypeErrorwill be raised. By convention,Falseis used for false andTruefor true. There are no implied relationships among the comparison operators. The truth ofx==ydoes not imply thatx!=yis false. Accordingly, when defining__eq__(), one should also define__ne__()so that the operators will behave as expected. There are no reflected (swapped-argument) versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather,__lt__()and__gt__()are each other's reflection,__le__()and__ge__()are each other's reflection, and__eq__()and__ne__()are their own reflection. Arguments to rich comparison methods are never coerced. A rich comparison method may returnNotImplementedif it does not implement the operation for a given pair of arguments.
__cmp__(self, other)-
Called by comparison operations if rich comparison (see above) is not
defined. Should return a negative integer if
self < other, zero ifself == other, a positive integer ifself > other. If no__cmp__(),__eq__()or__ne__()operation is defined, class instances are compared by object identity ("address"). See also the description of__hash__()for some important notes on creating objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by__cmp__()has been removed since Python 1.5.)
__rcmp__(self, other)- No longer supported since version 2.1.
__hash__(self)-
Called for the key object for dictionary
operations, and by the built-in function
hash(). Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If a class does not define a__cmp__()method it should not define a__hash__()operation either; if it defines__cmp__()or__eq__()but not__hash__(), its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a__cmp__()or__eq__()method, it should not implement__hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket). (Changed in Python version 2.5)
__nonzero__(self)-
Called to implement truth value testing, and the built-in operation
bool(); should returnFalseorTrue, or their integer equivalents0or1. When this method is not defined,__len__()is called, if it is defined (see below). If a class defines neither__len__()nor__nonzero__(), all its instances are considered true.
__unicode__(self)-
Called to implement the
unicode()builtin; should return a Unicode object. When this method is not defined, string conversion is attempted, and the result of string conversion is converted to Unicode using the system default encoding.
| ISBN 0954161785 | Python Language Reference Manual | See the print edition |