Next: Special methods for Up: Special method names Previous: Special method names

Special methods for any type

__init__(self, args...)
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 must explicitly call it to ensure proper initialization of the base class part of the instance.

__del__(self)
Called when the instance is about to be destroyed. If a base class has an __del__ method the derived class's __del__ method must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possible 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. Also note that it is not guaranteed that __del__ methods are called for objects that still exist when the interpreter exits.

__repr__(self)
Called by the repr() built-in function and by conversions (reverse quotes) to compute the string representation of an object.

__str__(self)
Called by the str() built-in function and by the print statement compute the string representation of an object.

__cmp__(self, other)
Called by all comparison operations. Should return -1 if self < other, 0 if self == other, +1 if self > other. If no __cmp__ operation is defined, class instances are compared by object identity (``address''). (Implementation note: due to limitations in the interpreter, exceptions raised by comparisons are ignored, and the objects will be considered equal in this case.)

__hash__(self)
Called by 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 exclusing 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__ but not __hash__ its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a __cmp__ method it should not implement __hash__, since the dictionary implementation assumes that a key's hash value is a constant.



Next: Special methods for Up: Special method names Previous: Special method names


guido@cwi.nl