Python special methods (Basic Customizations) 

Joined:
04/09/2007
Posts:
753

April 18, 2011 12:10:37    Last update: April 18, 2011 12:14:24
Python defines a long list of special methods to customize class behavior. This is a short list for the Basic Customizations.

MethodDescription
object.__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.

__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.
object.__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...]).
object.__del__(self)This is the destructor, called when the instance is about to be destroyed. 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.
object.__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).
object.__str__(self)Called by the str() built-in function and by the print statement to compute the “informal” string representation of an object.
object.__lt__(self,other)
object.__le__(self,other)
object.__eq__(self,other)
object.__ne__(self,other)
object.__gt__(self,other)
object.__ge__(self,other)
These are the so-called “rich comparison” methods, and are called for comparison operators in preference to __cmp__() below.
object.__cmp__(self,other)Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.
object.__hash__(self)Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict.

__hash__() should return an integer. The only required property is that objects which compare equal have the same hash value
object.__nonzero__(self)Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1.
object.__unicode__(self)Called to implement unicode() built-in; should return a Unicode object.
Share |
| Comment  | Tags